├── .Rbuildignore ├── .gitignore ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── R ├── RcppExports.R ├── TMBtools-package.R ├── export_models.R ├── gamma_ADFun.R ├── hadamard.R ├── helpers.R ├── norm_ADFun.R ├── old │ └── tmb_package_skeleton.R ├── tmb_create_package.R └── use_tmb.R ├── README.md ├── examples ├── tmb_create_package.R └── tmb_package_skeleton.R ├── inst ├── include │ └── TMBtools │ │ └── MatrixIP.hpp └── templates │ ├── GammaNLL.hpp │ ├── Makevars │ ├── Makevars.win │ ├── NAMESPACE │ ├── NormalNLL.hpp │ ├── TMBExports.cpp │ ├── compile.R │ ├── gamma_ADFun.R │ ├── init_dummy_file.cpp │ ├── norm_ADFun.R │ ├── old │ ├── DESCRIPTION │ ├── Read_and_delete_me │ └── tmb_examples.R │ ├── package.R │ ├── test-gamma_ADFun.R │ └── test-norm_ADFun.R ├── man ├── TMBtools-package.Rd ├── export_models.Rd ├── gamma_ADFun.Rd ├── hadamard.Rd ├── norm_ADFun.Rd ├── tmb_create_package.Rd └── use_tmb.Rd ├── src ├── Hadamard.cpp ├── Makevars ├── Makevars.win ├── RcppExports.cpp └── TMB │ ├── GammaNLL.hpp │ ├── NormalNLL.hpp │ ├── Rxz_dpd.hpp │ ├── TMBtools_TMBExports.cpp │ ├── compile.R │ ├── xRy_dpd.hpp │ ├── xRy_pdp.hpp │ ├── xRz_pdd.hpp │ └── ySx_pdp.hpp ├── tests ├── testthat.R └── testthat │ ├── old │ └── test-lm_eigen.R │ ├── test-aMb.R │ ├── test-gamma_ADFun.R │ ├── test-hadamard.R │ └── test-norm_ADFun.R └── vignettes ├── .gitignore ├── GammaNLL.hpp ├── MyTMBPackage_TMBExports.cpp ├── NormalNLL.cpp ├── NormalNLL.hpp └── TMBtools.Rmd /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^LICENSE$ 2 | ^README\.md$ 3 | ^examples$ 4 | ^doc$ 5 | ^Meta$ 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # template .gitignore for R packages 2 | 3 | # R 4 | *.Rhistory 5 | *.Rapp.history 6 | vignettes/.build.timestamp 7 | 8 | # C++ 9 | *.o 10 | *.so 11 | *.dll 12 | 13 | # osx 14 | *.DS_Store 15 | 16 | # devtools 17 | /doc/ 18 | /Meta/ 19 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: TMBtools 2 | Type: Package 3 | Title: Tools for Developing R Packages Interfacing with 'TMB' 4 | Version: 0.9.2 5 | Date: 2022-02-13 6 | Authors@R: person("Martin", "Lysy", 7 | email = "mlysy@uwaterloo.ca", 8 | role = c("aut", "cre")) 9 | Description: Provides helper functions for creating packages which contain 'TMB' source code. 10 | License: GPL (>= 2) 11 | Imports: 12 | Rcpp (>= 1.0.0), 13 | TMB (>= 1.7.15), 14 | usethis (>= 2.0.0), 15 | withr, 16 | fs, 17 | desc, 18 | utils, 19 | rprojroot 20 | LinkingTo: 21 | Rcpp, 22 | TMB 23 | Suggests: 24 | testthat, 25 | numDeriv, 26 | knitr, 27 | rmarkdown, 28 | devtools (>= 2.3.0), 29 | pkgbuild 30 | RoxygenNote: 7.1.2 31 | Encoding: UTF-8 32 | VignetteBuilder: knitr 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(export_models) 4 | export(gamma_ADFun) 5 | export(hadamard) 6 | export(norm_ADFun) 7 | export(tmb_create_package) 8 | export(use_tmb) 9 | importFrom(Rcpp,evalCpp) 10 | importFrom(usethis,ui_code_block) 11 | importFrom(usethis,ui_done) 12 | importFrom(usethis,ui_info) 13 | importFrom(usethis,ui_line) 14 | importFrom(usethis,ui_path) 15 | importFrom(usethis,ui_stop) 16 | importFrom(usethis,ui_todo) 17 | importFrom(usethis,ui_value) 18 | importFrom(usethis,use_directory) 19 | useDynLib(TMBtools, .registration = TRUE); useDynLib(TMBtools_TMBExports) 20 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | .hadamard <- function(A, B) { 5 | .Call(`_TMBtools_hadamard`, A, B) 6 | } 7 | 8 | -------------------------------------------------------------------------------- /R/TMBtools-package.R: -------------------------------------------------------------------------------- 1 | #' Tools for developing \R packages interfacing with \pkg{TMB}. 2 | #' 3 | #' @details Currently, the packages provides two main functions \code{\link{tmb_create_package}} and \code{\link{export_models}}, for creating packages containing \pkg{TMB} source code, and updating the package's compile instructions when new \pkg{TMB} models are added. Please see walkthrough in \code{vignette(p = "TMBtools")}. 4 | #' @rawNamespace useDynLib(TMBtools, .registration = TRUE); useDynLib(TMBtools_TMBExports) 5 | #' @importFrom usethis use_directory ui_line ui_info ui_value ui_todo ui_code_block ui_path ui_done ui_stop 6 | #' @importFrom Rcpp evalCpp 7 | "_PACKAGE" 8 | -------------------------------------------------------------------------------- /R/export_models.R: -------------------------------------------------------------------------------- 1 | #' Create C++ code to export \pkg{TMB} models from package. 2 | #' 3 | #' @param pkg Character string: any subdirectory of the package source code. 4 | #' @return Invisible; called for its side effects. 5 | #' 6 | #' @details \pkg{TMB} models should be saved as C++ header files of the form \code{src/TMB/*.hpp}, and written almost exactly as with usual \pkg{TMB} \code{*.cpp} models. So for example, \code{src/TMB/ModelA.hpp} would be written as: 7 | #' \preformatted{ 8 | #' // __DO NOT__ '#include ' as file is not include-guarded 9 | #' 10 | #' #undef TMB_OBJECTIVE_PTR 11 | #' #define TMB_OBJECTIVE_PTR obj 12 | #' 13 | #' // name of function _must_ match file name (ModelA) 14 | #' template 15 | #' Type ModelA(objective_function* obj) { 16 | #' 17 | #' // _exactly_ the same code as for usual 'ModelA.cpp' 18 | #' 19 | #' } 20 | #' 21 | #' #undef TMB_OBJECTIVE_PTR 22 | #' #define TMB_OBJECTIVE_PTR this 23 | #' } 24 | #' The function \code{export_models} creates a file \code{src/TMB/pkgname_TMBExports.cpp} containing a single \pkg{TMB} model object which dispatches the appropriate \code{ModelA.hpp}, \code{ModelB.hpp}, etc. using \code{if/else} statements. At the \R level, the correct model is invoked from \code{TMB::MakeADFun} exactly as for a single \pkg{TMB} model, except the \code{data} list argument gets an additional element \code{model} specifying the name of the model, e.g., \code{model = "ModelA"}. 25 | #' 26 | #' \code{export_models} assumes that each file of the form \code{src/TMB/*.hpp} contains \emph{exactly one} \pkg{TMB} model. In order for these to \code{#include} additional \code{.hpp} files, these additional files must be placed either in a subfolder of \code{src/TMB}, or in (a subfolder of) \code{inst/include}. The advantage of the latter approach is that the additional files are available to other \R packages via \code{LinkingTo: pkgname} is the other package's \code{DESCRIPTION}. If the latter approach is used, the \code{TMB} compiler must be notified of the additional include directory. This is done by setting the \code{TMB_FLAGS} in \code{src/Makevars[.win]} to 27 | #' \preformatted{ 28 | #' TMB_FLAGS = -I"../../inst/include" 29 | #' } 30 | #' Other flags specific to the \pkg{TMB} compiler can be set here as well, as can the usual \code{CXX_FLAGS}, etc. for other source code in \code{src}, which is compiled independently of that in \pkg{src/TMB}. 31 | #' 32 | #' @seealso \code{\link{use_tmb}} 33 | #' @export 34 | export_models <- function(pkg = ".") { 35 | currwd <- getwd() 36 | on.exit(setwd(currwd)) 37 | usethis::local_project(pkg, quiet = TRUE) 38 | root <- usethis::proj_get() #.package_root(pkg) 39 | setwd(root) 40 | pkg_name <- get_package(root) 41 | tmb_path <- file.path("src", "TMB") 42 | tmb_main <- file.path(tmb_path, paste0(pkg_name, "_TMBExports.cpp")) 43 | # if not TMB-generated don't overwrite 44 | check_tmb_generated(tmb_main) 45 | # determine template values: 46 | # include files 47 | model_files <- list.files(path = tmb_path, pattern = "[.]hpp$", 48 | ignore.case = TRUE) 49 | incl_lines <- paste0('#include "', model_files, '"', collapse = '\n') 50 | # if statements 51 | # model names: no path and no extension 52 | model_names <- sub(pattern = "(.*?)\\..*$", 53 | replacement = "\\1", basename(model_files)) 54 | if(length(model_names) > 0) { 55 | if_lines <- paste0('if(model == "', model_names, '") {\n', 56 | ' return ', model_names, '(this);\n', 57 | ' }', collapse = ' else ') 58 | if_lines <- paste0(if_lines, ' else {\n', 59 | ' Rf_error("Unknown model.");\n }') 60 | } else { 61 | if_lines <- ' Rf_error("Unknown model.");' 62 | } 63 | use_template(template = "TMBExports.cpp", package = "TMBtools", 64 | data = list(pkg = pkg_name, 65 | includes = incl_lines, 66 | switches = if_lines), 67 | save_as = tmb_main) 68 | } 69 | 70 | ## ' @param model_files Character vector of header files relative to \code{src/TMB} listing the \pkg{TMB} models to export. If missing defaults to all \code{hpp} files in \code{src/TMB}. \strong{Note:} Always use forward slash "/" to separate directories, even on Windows. 71 | 72 | 73 | ## # path to TMB templates 74 | ## .template_file <- function(...) { 75 | ## system.file("templates", ..., package = "TMBtools") 76 | ## } 77 | 78 | ## # find package root: basically copied from devtools 79 | ## .package_root <- function(path = ".") { 80 | ## if(!is.character(path) || length(path) != 1) { 81 | ## stop("'path' must be a string.", call. = FALSE) 82 | ## } 83 | ## path <- sub("/*$", "", normalizePath(path, mustWork = FALSE)) 84 | ## if(!file.exists(path)) { 85 | ## stop("Can't find '", path, "'.", call. = FALSE) 86 | ## } 87 | ## if(!file.info(path)$isdir) { 88 | ## stop("'", path, "' is not a directory.", call. = FALSE) 89 | ## } 90 | ## while(!file.exists(file.path(path, "DESCRIPTION"))) { 91 | ## path <- dirname(path) 92 | ## if(identical(path, dirname(path))) { 93 | ## stop("Could not find package root.", call. = FALSE) 94 | ## } 95 | ## } 96 | ## path 97 | ## } 98 | 99 | -------------------------------------------------------------------------------- /R/gamma_ADFun.R: -------------------------------------------------------------------------------- 1 | #' Create a \code{TMB::ADFun} object for the gamma likelihood. 2 | #' 3 | #' @param x Vector of observations. 4 | #' @return A list as returned by \code{TMB::MakeADFun} representing the negative loglikelihood of a gamma distribution. 5 | #' @export 6 | gamma_ADFun <- function(x) { 7 | TMB::MakeADFun(data = list(model = "GammaNLL", x = x), 8 | parameters = list(alpha = 1, beta = 1), 9 | DLL = "TMBtools_TMBExports", silent = TRUE) 10 | } 11 | -------------------------------------------------------------------------------- /R/hadamard.R: -------------------------------------------------------------------------------- 1 | #' Calculate the Hadamard product between two matrices. 2 | #' 3 | #' Commonly referred to as elementwise matrix multiplication. 4 | #' 5 | #' @param A First matrix. 6 | #' @param B Second matrix of same dimensions as \code{A}. 7 | #' @return Elementwise product between the two matices. 8 | #' @export 9 | hadamard <- function(A, B) { 10 | if(!is.matrix(A) || !is.matrix(B) || !identical(dim(A), dim(B))) { 11 | stop("A and B must be matrices of the same dimension.") 12 | } 13 | .hadamard(A = A, B = B) 14 | } 15 | -------------------------------------------------------------------------------- /R/helpers.R: -------------------------------------------------------------------------------- 1 | #--- helper functions ---------------------------------------------------------- 2 | 3 | # formats useDynLib 4 | use_dynlib <- function(dynlibs) { 5 | out <- paste0("useDynLib(", dynlibs, ")") 6 | out <- paste0(out, collapse = "; ") 7 | out 8 | } 9 | 10 | # adds a file to the package 11 | use_file <- function(fl, ...) { 12 | if(!file.exists(fl)) ui_stop("File {ui_path(fl)} doesn't exist.") 13 | path <- file.path(..., basename(fl)) 14 | success <- file.copy(from = fl, 15 | to = file.path(usethis::proj_get(), path)) 16 | if(success) { 17 | ui_done("Writing {ui_path(path)}") 18 | } 19 | } 20 | 21 | # silently executes usethis commands 22 | use_silent <- function(code) { 23 | if(!missing(code)) { 24 | withr::with_options(list(usethis.quiet = TRUE), code = code) 25 | } 26 | } 27 | 28 | # needs init if src has no files (except directories) 29 | check_needs_init <- function(root) { 30 | src_files <- dir(path = file.path(root, "src"), full.names = TRUE) 31 | length(src_files) == 0 || all(dir.exists(src_files)) 32 | } 33 | 34 | # check whether license is gpl (>=2) compatible 35 | check_gpl <- function(root) { 36 | lic <- read.dcf(file = file.path(root, "DESCRIPTION"), 37 | fields = "License")[1] 38 | if(is.na(lic)) { 39 | lic <- FALSE 40 | } else { 41 | # has a license, check compatibility 42 | lic <- toupper(gsub("[[:space:]]+", "", lic)) 43 | lic <- gsub("(\\|LICENSE|\\|LICENCE)", "", lic) 44 | lic <- gsub("[^[:alnum:]]+", "", lic) 45 | lic <- lic %in% c("GPL2", "GPL3", "AGPL3") 46 | } 47 | if(!lic) { 48 | ui_todo("{ui_value(get_package(root))} legally requires GPL-2 compatible license to distribute {ui_value('TMB')} code.") 49 | ui_line("To enable this set the following in DESCRIPTION:") 50 | message("") 51 | ui_code_block("License: GPL (>= 2)") 52 | message("") 53 | } 54 | } 55 | 56 | # identical to usethis::use_template, except: 57 | # 1. package defaults to TMBtools 58 | # 2. never overwrites if file exists 59 | use_template <- function(template, save_as = template, 60 | data = list(), ignore = FALSE, 61 | open = FALSE, package = "TMBtools") { 62 | usethis::local_project() 63 | if(file.exists(file.path(usethis::proj_get(), save_as))) { 64 | ui_line("File {ui_path(save_as)} already exists. Not overwritten.") 65 | } else { 66 | usethis::use_template(template = template, 67 | save_as = save_as, 68 | data = data, ignore = ignore, 69 | open = open, package = package) 70 | } 71 | } 72 | 73 | # get package name 74 | get_package <- function(root) { 75 | read.dcf(file = file.path(root, "DESCRIPTION"), fields = "Package")[1] 76 | } 77 | 78 | # check if file was autogenerated by TMBtools 79 | check_tmb_generated <- function(tmb_main) { 80 | tmb_str <- "// Generated by TMBtools: do not edit by hand" 81 | if(file.exists(tmb_main)) { 82 | if(readLines(tmb_main)[1] != tmb_str) { 83 | tmb_main <- paste0('src/TMB/', basename(tmb_main)) 84 | ui_stop("{ui_path(tmb_main)} exists but not generated by TMBtools. Not overwritten.") 85 | } else { 86 | file.remove(tmb_main) 87 | } 88 | } 89 | } 90 | 91 | # check if path is nested in another package 92 | check_pkg_nested <- function(path) { 93 | usethis::local_project(path = path, force = TRUE, setwd = FALSE, quiet = TRUE) 94 | pkg <- tryCatch(rprojroot::find_root("DESCRIPTION", path), 95 | error = function(e) NULL) 96 | ## currwd <- getwd() 97 | ## on.exit(setwd(currwd)) 98 | ## setwd(path) 99 | ## proj <- usethis::proj_get() 100 | if(!is.null(pkg)) { 101 | ui_stop("{ui_value('usethis::create_package')} cannot create a package inside existing package {ui_value(pkg)}.") 102 | } 103 | } 104 | 105 | 106 | # add TMB specific instructions to NAMESPACE file 107 | add_tmb_namespace <- function(root, pkg, dynlibs) { 108 | nsp <- file.path(root, "NAMESPACE") 109 | # check if the NAMESPACE has the correct dynlibs 110 | has_tmb_nsp <- rm_white(use_dynlib(dynlibs)) 111 | has_tmb_nsp <- gsub("([.]|\\(|\\))", "\\\\\\1", has_tmb_nsp) 112 | has_tmb_nsp <- file.exists(nsp) && 113 | any(grepl(pattern = paste0("^(", has_tmb_nsp, ")$"), 114 | x = rm_white(readLines(nsp)))) 115 | # check if package uses roxygen 116 | has_roxy <- !all(is.na(read.dcf(file.path(root, "DESCRIPTION"), 117 | fields = c("Roxygen", "RoxygenNote")))) 118 | if(!has_tmb_nsp) { 119 | has_nsp <- file.exists(nsp) 120 | if(!has_nsp) { 121 | # add Namespace file (probably only happens in tmb_create_package) 122 | use_template(template = "NAMESPACE", package = "TMBtools", 123 | data = list(usedl = use_dynlib(dynlibs))) 124 | } 125 | if(has_roxy) { 126 | # check if package has "pkgname{-package}.R" file 127 | has_pkgdoc <- file.path(root, "R", 128 | paste0(pkg, c(".R", "-package.R"))) 129 | has_pkgdoc <- any(file.exists(has_pkgdoc)) 130 | if(!has_pkgdoc) { 131 | # create a default usethis namespace 132 | use_template(template = "package.R", package = "TMBtools", 133 | save_as = file.path("R", paste0(pkg, "-package.R")), 134 | data = list(usedl = use_dynlib(dynlibs))) 135 | ui_done("Done!") 136 | if(has_nsp) { 137 | # probably only avoided with tmb_create_package 138 | ui_todo("Run roxygen on package to update NAMESPACE.") 139 | } 140 | } else { 141 | # user has to manually update namespace via roxygen 142 | ui_done("Done!") 143 | ui_todo("Add the following roxygen comment to update the NAMESPACE:") 144 | message() 145 | ui_code_block(paste0("#' @rawNamespace ", use_dynlib(dynlibs))) 146 | message("") 147 | } 148 | } else { 149 | # user has to manually update namespace by hand 150 | ui_done("Done!") 151 | ui_todo("Add the following line to the NAMESPACE file:\n") 152 | message("") 153 | ui_line(use_dynlib(dynlibs)) 154 | message("") 155 | } 156 | } else { 157 | ui_done("Done!") 158 | } 159 | } 160 | 161 | # remove all whitespace from a character vector 162 | rm_white <- function(x) gsub("[[:space:]]", "", x) 163 | 164 | ## # similar to usethis::create_package but with fewer options and no prompts 165 | ## create_package <- function(path, fields) { 166 | ## path <- fs::path_expand(path) 167 | ## name <- fs::path_file(path) 168 | ## fs::dir_create(path) 169 | ## old_project <- usethis::proj_set(path, force = TRUE) 170 | ## on.exit(usethis::proj_set(old_project), add = TRUE) 171 | ## use_directory("R") 172 | ## usethis::use_description(fields) 173 | ## invisible(usethis::proj_get()) 174 | ## } 175 | -------------------------------------------------------------------------------- /R/norm_ADFun.R: -------------------------------------------------------------------------------- 1 | #' Create a \code{TMB::ADFun} object for the normal likelihood. 2 | #' 3 | #' @param x Vector of observations. 4 | #' @return A list as returned by \code{TMB::MakeADFun} representing the negative loglikelihood of a univariate normal. 5 | #' @export 6 | norm_ADFun <- function(x) { 7 | TMB::MakeADFun(data = list(model = "NormalNLL", x = x), 8 | parameters = list(mu = 0, sigma = 1), 9 | DLL = "TMBtools_TMBExports", silent = TRUE) 10 | } 11 | -------------------------------------------------------------------------------- /R/old/tmb_package_skeleton.R: -------------------------------------------------------------------------------- 1 | #' Create a skeleton for a new package depending on \pkg{TMB}. 2 | #' 3 | #' @param name Character string: the package name and directory name for the package. See \code{utils::package.skeleton}. 4 | #' @param list Character vector naming the \R objects to put in the package. See \code{utils::package.skeleton}. 5 | #' @param environment An environment where objects are looked for. See \code{utils::package.skeleton}. 6 | #' @param path Path to put the package directory in. 7 | #' @param force If \code{FALSE} will not overwrite an existing directory. 8 | #' @param code_files A character vector with the paths to \R code files to build the package around. \code{utils::package.skeleton}. 9 | #' @param cpp_files A character vector with the paths to C++ source files to add to the package, or a logical. If a non-empty character vector or \code{TRUE}, the package will use \pkg{Rcpp} features. 10 | #' @param tmb_files A charactor vector with the paths to \pkg{TMB} source files to add to the package. 11 | #' @param example_code If \code{TRUE}, example \pkg{TMB} source code is added to the package. 12 | #' 13 | #' @details The created package is compatible with \pkg{roxygen2}-style documentation. That is, a package passing \code{R CMD check --as-cran} is created out-of-the-box upon running the code in \strong{Examples}. 14 | #' @example examples/tmb_package_skeleton.R 15 | #' @export 16 | tmb_package_skeleton <- function(name = "anRpackage", 17 | list = character(), 18 | environment = .GlobalEnv, 19 | path = ".", force = FALSE, 20 | code_files = character(), 21 | cpp_files = character(), 22 | tmb_files = character(), 23 | example_code = TRUE) { 24 | # argument checks 25 | if(is.logical(cpp_files)) { 26 | use_Rcpp <- cpp_files 27 | cpp_files <- character() 28 | } else { 29 | if(!is.character(cpp_files)) { 30 | stop("'cpp_files' must be a character vector.") 31 | } else { 32 | use_Rcpp <- TRUE 33 | } 34 | } 35 | if(!is.character(tmb_files)) 36 | stop("'tmb_files' must be a character vector.") 37 | 38 | # create package skeleton 39 | # need dummy object in case no R objects are given 40 | env <- parent.frame(1) 41 | dummy_name <- basename(tempfile("package_skeleton_dummy_object_")) 42 | assign(dummy_name, function() {}, envir = env) 43 | # make sure dummy object gets deleted 44 | on.exit(rm(list = dummy_name, envir = env)) 45 | call <- match.call() 46 | call[[1]] <- quote(utils::package.skeleton) 47 | call <- call[ c(1L, which(names(call) %in% names(formals(utils::package.skeleton)))) ] 48 | tryCatch(suppressMessages(eval(call, envir = env)), error = function(e) { 49 | stop("error while calling `package.skeleton` : ", conditionMessage(e)) 50 | }) 51 | root <- file.path(path, name) 52 | # remove dummy object from package 53 | unlink(file.path(root, "R", paste0(dummy_name, ".R"))) 54 | # remove R/TMBExports-internal.R if accidentally created 55 | if(file.exists(x <- file.path(root, "R", paste0(name, "-internal.R")))) { 56 | unlink(x) 57 | } 58 | # delete contents of man/ so package installs without errors 59 | file.remove(list.files(file.path(root, "man"), full.names = TRUE)) 60 | message("Created basic package skeleton...") 61 | 62 | # update DESCRIPTION file 63 | desc <- file.path(root, "DESCRIPTION") 64 | if(file.exists(desc)) { 65 | imports <- "TMB" 66 | if(use_Rcpp) { 67 | imports <- c(imports, 68 | sprintf("Rcpp (>= %s)", 69 | utils::packageDescription("Rcpp")[["Version"]])) 70 | } 71 | linkingto <- c("TMB", if(use_Rcpp) "Rcpp") 72 | x <- read.dcf(desc) 73 | x[, "License"] <- "GPL (>= 2)" 74 | x <- cbind(x, "Imports" = paste0(imports, collapse = ", ")) 75 | x <- cbind(x, "LinkingTo" = paste0(linkingto, collapse = ", ")) 76 | x <- cbind(x, "Encoding" = "UTF-8") 77 | # the following avoids NOTE from R CMD check --as-cran 78 | x[, "Description"] <- paste0(x[, "Description"], ".") 79 | message("Updated 'DESCRIPTION'...") 80 | write.dcf(x, file = desc) 81 | } 82 | 83 | # update NAMESPACE file 84 | nspc <- file.path(root, "NAMESPACE") 85 | x <- readLines(.template_file("NAMESPACE")) 86 | if(getRversion() >= "3.4.0") { 87 | usedl <- sprintf("useDynLib(%s, .registration=TRUE)", name) 88 | } else { 89 | usedl <- sprintf("useDynLib(%s)", name) 90 | } 91 | usedl <- c(usedl, sprintf("useDynLib(%s_TMBExports)", name)) 92 | x <- c(x, paste0(usedl, collapse = "; "), "importFrom(Rcpp, evalCpp)") 93 | cat(x, sep = "\n", file = nspc) 94 | message("Updated 'NAMESPACE'...") 95 | 96 | # create corresponding *-package.R file 97 | x <- readLines(.template_file("package.R")) 98 | if(use_Rcpp) { 99 | x <- sub("@@use_Rcpp@@", "@importFrom Rcpp evalCpp", x) 100 | } else { 101 | x <- x[!grepl("@@use_Rcpp@@", x)] 102 | } 103 | x <- sub("@@usedl@@", paste0(usedl, collapse = "; "), x) 104 | cat(x, sep = "\n", file = file.path(root, "R", paste0(name, "-package.R"))) 105 | message("Added 'R/", name, 106 | "-package.R' with 'roxygen2'-style 'NAMESPACE' directives...") 107 | 108 | # add files to src 109 | if(!dir.exists(x <- file.path(root, "src", "TMB"))) { 110 | dir.create(x, recursive = TRUE) 111 | } 112 | if(length(cpp_files) > 0) { 113 | file.copy(from = cpp_files, to = file.path(root, "src"), recursive = TRUE) 114 | message("Added 'cpp_files' to 'src'...") 115 | } else { 116 | # include a dummy file, otherwise useDynLib(name) will fail. 117 | init_file <- file.path(root, "src", "init_dummy_file.cpp") 118 | x <- readLines(.template_file("init_dummy_file.cpp")) 119 | x <- gsub("@@pkg@@", name, x) 120 | x <- sub("@@usedl_pkg@@", usedl[1], x) 121 | cat(x, sep = "\n", file = init_file) 122 | } 123 | 124 | # add files to src/TMB 125 | if(length(tmb_files) > 0) { 126 | file.copy(from = tmb_files, to = file.path(root, "src", "TMB"), 127 | recursive = TRUE) 128 | message("Added 'tmb_files' to 'src/TMB'...") 129 | } 130 | file.copy(from = .template_file(c("Makevars", "Makevars.win")), 131 | to = file.path(root, "src"), recursive = TRUE) 132 | file.copy(from = .template_file("compile.R"), 133 | to = file.path(root, "src", "TMB"), recursive = TRUE) 134 | message("Added TMB system files 'src/Makevars[.win]' and 'src/TMB/compile.R'...") 135 | 136 | # example code 137 | if(example_code) { 138 | file.copy(from = .template_file(c("NormNLL.hpp", "GammaNLL.hpp")), 139 | to = file.path(root, "src", "TMB"), recursive = TRUE) 140 | x <- readLines(.template_file("tmb_examples.R")) 141 | x <- gsub("@@pkg@@", name, x) 142 | cat(x, sep = "\n", file = file.path(root, "R", "tmb_examples.R")) 143 | message("Added TMB example code...") 144 | } 145 | 146 | # create name_TMBExports.cpp 147 | export_models(pkg = root) 148 | message("Exported TMB models via 'src/TMB/", name, "_TMBExports.cpp'...") 149 | # create Read_and_delete_me file 150 | x <- readLines(.template_file("Read_and_delete_me")) 151 | if(length(cpp_files) == 0) { 152 | x <- gsub("@@use_Rcpp@@", "", x) 153 | } else { 154 | x <- x[-(grep("@@use_Rcpp@@", x)+0:2)] 155 | } 156 | x <- gsub("@@usedl_pkg@@", usedl[1], x) 157 | x <- gsub("@@usedl_tmb@@", usedl[2], x) 158 | cat(x, sep = "\n", file = file.path(root, "Read-and-delete-me")) 159 | message("Done. Additional TMB-specific notes in 'Read-and-delete-me'.") 160 | invisible(NULL) 161 | } 162 | 163 | # path to TMB templates 164 | .template_file <- function(...) { 165 | system.file("templates", ..., package = "RcppTMBTest") 166 | } 167 | -------------------------------------------------------------------------------- /R/tmb_create_package.R: -------------------------------------------------------------------------------- 1 | #' Create a \pkg{TMB} package. 2 | #' 3 | #' @param path Absolute or relative path to where the package is to be created. If the path exists, it is used. If it does not exist, it is created, provided that the parent path exists. 4 | #' @param tmb_files Optional character vector of \pkg{TMB} header files to include in the package. See \strong{Details}. 5 | #' @param fields,open Same function as corresponding arguments in \code{usethis::create_package}. 6 | #' @param example_code Adds example \pkg{TMB} files to the package (see \strong{Examples}). 7 | #' 8 | #' @return Nothing; called for its side effect. 9 | #' 10 | #' @details Calls \code{usethis::create_package} followed by \code{\link{use_tmb}} and \code{\link{export_models}}, which add the \pkg{TMB} infrastructure and initialize the provided \pkg{TMB} model list, respectively. Please see documentation for these functions as to how exactly a \pkg{TMB}-enabled package should be set up. 11 | #' 12 | #' @example examples/tmb_create_package.R 13 | #' @seealso \code{\link{use_tmb}} for adding \pkg{TMB} infrastructure to an existing package,\code{\link{export_models}} for adding \pkg{TMB} model files after the package is created. 14 | #' @export 15 | tmb_create_package <- function(path, 16 | tmb_files = character(), 17 | fields = NULL, 18 | open = interactive(), 19 | example_code = FALSE) { 20 | ## if(!is.character(tmb_files)) { 21 | ## stop("'tmb_files' must be a character vector.") 22 | ## } 23 | # create package skeleton 24 | ui_info("Creating package skeleton...") 25 | currwd <- getwd() 26 | # in case package creation fails, don't change directories 27 | on.exit(setwd(currwd)) 28 | # check if path is inside another project 29 | check_pkg_nested(path) 30 | # run create_package silently, so need to disable invocations of ui prompts 31 | if(dir.exists(path)) { 32 | ui_stop("{ui_path(path)} already exists.") 33 | } 34 | dir.create(path, recursive = TRUE) 35 | # add license 36 | if(is.null(fields) || is.null(fields$License)) { 37 | fields$License <- "GPL (>= 2)" 38 | } 39 | use_silent({ 40 | ## create_package(path = path, fields = fields) 41 | pkgdir <- usethis::create_package(path = path, 42 | fields = fields, 43 | rstudio = FALSE, 44 | ## check_name = check_name, 45 | open = FALSE) 46 | }) 47 | setwd(pkgdir) 48 | file.remove("NAMESPACE") 49 | if(example_code) { 50 | tmb_files <- c(tmb_files, 51 | system.file("templates", "NormalNLL.hpp", 52 | package = "TMBtools"), 53 | system.file("templates", "GammaNLL.hpp", 54 | package = "TMBtools")) 55 | } 56 | if(length(tmb_files) > 0) { 57 | if(anyDuplicated(basename(tmb_files))) { 58 | ui_stop("TMB filenames {ui_path(basename(tmb_files))} must be unique.") 59 | } 60 | # copy TMB files 61 | use_silent(usethis::proj_set(pkgdir)) 62 | ui_info("Copying TMB files...") 63 | use_directory("src") 64 | use_directory("src/TMB") 65 | setwd(currwd) 66 | sapply(tmb_files, use_file, "src", "TMB") 67 | setwd(pkgdir) 68 | if(!open) use_silent(usethis::proj_set(NULL)) 69 | } 70 | use_tmb() 71 | export_models() 72 | if(open) { 73 | usethis::proj_set(pkgdir) 74 | on.exit(setwd(pkgdir)) 75 | } 76 | } 77 | 78 | 79 | ## create_package <- function(path, fields) { 80 | ## path <- fs::path_expand(path) 81 | ## name <- fs::path_file(path) 82 | ## fs::dir_create(path) 83 | ## old_project <- usethis::proj_set(path, force = TRUE) 84 | ## on.exit(usethis::proj_set(old_project), add = TRUE) 85 | ## use_directory("R") 86 | ## usethis::use_description(fields) 87 | ## invisible(usethis::proj_get()) 88 | ## } 89 | 90 | ## { 91 | ## path <- user_path_prep(path) 92 | ## check_path_is_directory(path_dir(path)) 93 | ## name <- path_file(path) 94 | ## if (check_name) { 95 | ## check_package_name(name) 96 | ## } 97 | ## check_not_nested(path_dir(path), name) 98 | ## create_directory(path) 99 | ## old_project <- proj_set(path, force = TRUE) 100 | ## on.exit(proj_set(old_project), add = TRUE) 101 | ## use_directory("R") 102 | ## use_description(fields, check_name = check_name) 103 | ## use_namespace() 104 | ## if (rstudio) { 105 | ## use_rstudio() 106 | ## } 107 | ## if (open) { 108 | ## if (proj_activate(path)) { 109 | ## on.exit() 110 | ## } 111 | ## } 112 | ## invisible(proj_get()) 113 | ## } 114 | -------------------------------------------------------------------------------- /R/use_tmb.R: -------------------------------------------------------------------------------- 1 | #' Add \pkg{TMB} functionality to an existing package. 2 | #' 3 | #' @return Nothing; called for its side effects. 4 | #' @details Adds the following to the package: 5 | #' 6 | #' \itemize{ 7 | #' \item \code{src/TMB/compile.R}: runs the C++ compiler on \pkg{TMB} model files (see \code{\link{export_models}}). 8 | #' \item \code{src/Makevars[.win]}: ensures that \pkg{TMB} compilation does not affect that of other source files in \code{src}. 9 | #' \item \code{src/init_dummy_file.cpp}: needed to set \code{R_registerRoutines} if the package contains no other source code apart from what's in \code{src/TMB}. 10 | #' \item \code{Imports: TMB} and \code{LinkingTo: TMB} are added to the package's \code{DESCRIPTION}. 11 | #' \item An optional file \code{R/pkgname-package.R} with \pkg{roxygen2} \code{NAMESPACE} directives, if such a file does not exist. Otherwise, prints instructions as to how the \code{NAMESPACE} must be modified (see below). 12 | #' } 13 | #' 14 | #' Because of how \pkg{TMB} source files are compiled, at present the package must create two shared object (\code{.so}, \code{.dll}) files: \code{pkgname_TMBExports.so} for the \pkg{TMB} models, and \code{pkgname.so} for the usual package source code. In the \code{NAMESPACE} file, it is imperative that the latter be `useDynLib`ed before the former. The fail-safe \pkg{roxygen2} instruction for this is 15 | #' \preformatted{ 16 | #' #' @rawNamespace useDynLib(pkgname, .registration = TRUE); useDynLib(pkgname_TMBExports) 17 | #' } 18 | #' 19 | #' @seealso \code{\link{export_models}} for details on adding \pkg{TMB} model files after running \code{use_tmb}. 20 | #' @export 21 | use_tmb <- function() { 22 | root <- use_silent(usethis::proj_get()) 23 | pkg <- get_package(root) 24 | # create TMB infrastructure 25 | ui_info("Adding TMB infrastructure...") 26 | use_directory("src") 27 | use_directory(file.path("src", "TMB")) 28 | add_init <- check_needs_init(root) # check if C++ init file is needed 29 | use_template(template = "compile.R", package = "TMBtools", 30 | save_as = file.path("src", "TMB", "compile.R"), 31 | data = list(pkg = pkg)) 32 | use_template(template = "Makevars", package = "TMBtools", 33 | save_as = file.path("src", "Makevars")) 34 | use_template(template = "Makevars.win", package = "TMBtools", 35 | save_as = file.path("src", "Makevars.win")) 36 | # determine useDynLibs 37 | dynlibs <- paste0(pkg, 38 | c(ifelse(getRversion() >= "3.4.0", 39 | ", .registration=TRUE", ""), 40 | "_TMBExports")) 41 | # update DESCRIPTION file 42 | ui_info("Updating DESCRIPTION...") 43 | use_silent({ 44 | vers <- paste0(">= ", as.character(utils::packageVersion("TMB"))) 45 | desc::desc_set_dep(package = "TMB", type = "Imports", 46 | version = vers, 47 | file = file.path(root, "DESCRIPTION")) 48 | desc::desc_set_dep(package = "TMB", type = "LinkingTo", 49 | file = file.path(root, "DESCRIPTION")) 50 | ## usethis::use_package(package = "TMB", type = "LinkingTo", 51 | ## min_version = TRUE) 52 | ## usethis::use_package(package = "TMB", type = "Imports", 53 | ## min_version = TRUE) 54 | ## usethis::use_package(package = "TMB", type = "LinkingTo", 55 | ## min_version = NULL) 56 | }) 57 | ## use_description(fields = list(License = "GPL (>= 2)")) 58 | if(add_init) { 59 | # add C++ init file 60 | ## ui_info("Adding C++ init file...") 61 | use_template(template = "init_dummy_file.cpp", package = "TMBtools", 62 | save_as = file.path("src", "init_dummy_file.cpp"), 63 | data = list(usedl = use_dynlib(dynlibs[1]), pkg = pkg)) 64 | } 65 | # update Namespace directives 66 | add_tmb_namespace(root, pkg, dynlibs) 67 | if(add_init) { 68 | ui_todo("Delete {ui_path('src/init_dummy_file.cpp')} if C++ files are later added to {ui_path('src')}.") 69 | } 70 | check_gpl(root) 71 | invisible(NULL) 72 | } 73 | 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TMBtools: Tools for Developing R Packages Interfacing with TMB 2 | 3 | *Martin Lysy* 4 | 5 | --- 6 | 7 | ## Overview 8 | 9 | [**TMB**](https://github.com/kaskr/adcomp/wiki) is an R package providing a convenient interface to the [**CppAD**](https://coin-or.github.io/CppAD/doc/cppad.htm) C++ library for [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). More specifically for the purpose of statistical inference, **TMB** provides an automatic and extremely efficient implementation of [Laplace's method](https://en.wikipedia.org/wiki/Laplace%27s_method) to approximately integrate out the latent variables of a model *p(x | theta) = \int p(x, z | theta) dz* via numerical optimization. **TMB** is extensively [documented](http://kaskr.github.io/adcomp/_book/Introduction.html), and numerous [examples](http://kaskr.github.io/adcomp/_book/Examples.html#example-overview) indicate that it can be used to effectively handle tens to thousands of latent variables in a model. 10 | 11 | **TMB** was designed for users to compile and save standalone statistical models. Distributing one or more **TMB** models as part of an R package requires a nontrivial compilation process (`Makevars[.win]`), and some amount of boilerplate code. Thus, the purpose of **TMBtools** is to provide helper functions for the development of R packages which contain **TMB** source code, promoting effective **TMB** coding practices as discussed [below](#tmb-coding-practices). The main package functions are: 12 | 13 | - `tmb_create_package()`, which creates an R package infrastructure with the proper **TMB** compile instructions. 14 | 15 | - `use_tmb()`, which adds **TMB** functionality to an existing package. 16 | 17 | - `export_models()`, which updates the package's **TMB** compile instructions when new models are added. 18 | 19 | **Note to Developers:** While **TMBtools** depends on a number of packages to facilitate its work, none of these dependencies are passed on to your package, except **TMB** itself. 20 | 21 | ## Installation 22 | 23 | Install the R package [**devtools**](https://CRAN.R-project.org/package=devtools) package and run: 24 | ```r 25 | devtools::install_github("mlysy/TMBtools") 26 | testthat::test_package("TMBtools", reporter = "progress") # optionally run the unit tests 27 | ``` 28 | 29 | ## Quickstart 30 | 31 | As per the standard **TMB** [tutorial](https://github.com/kaskr/adcomp/wiki/Tutorial), a typical standalone **TMB** model defined in `ModelA.cpp` would look something like this: 32 | ```cpp 33 | /// @file ModelA.cpp 34 | 35 | #include 36 | 37 | template 38 | Type objective_function::operator() () { 39 | // model definition 40 | } 41 | ``` 42 | And would be compiled and called from R as follows: 43 | ```r 44 | TMB::compile("ModelA.cpp") # compile model 45 | dynload(TMB::dynlib("ModelA")) # link to R session 46 | 47 | # instantiate model object 48 | modA <- TMB::MakeADFun(data = data_list, 49 | parameters = param_list, 50 | DLL = "ModelA") 51 | 52 | modA$fn(other_param_list) # call its negative loglikelihood 53 | modA$gr(other_param_list) # negative loglikelihood gradient 54 | ``` 55 | To create an R package containing `ModelA`, we must convert `ModelA.cpp` to a header file `ModelA.hpp` and make a few minor modifications: 56 | ```cpp 57 | /// @file ModelA.hpp 58 | 59 | // **DON'T** #include as it is not include-guarded 60 | 61 | #undef TMB_OBJECTIVE_PTR 62 | #define TMB_OBJECTIVE_PTR obj 63 | 64 | // name of function below **MUST** match filename 65 | // (here it's ModelA) 66 | template 67 | Type ModelA(objective_function* obj) { 68 | // exactly same body as 69 | // `objective_function::operator()` 70 | // in `ModelA.cpp` 71 | } 72 | 73 | #undef TMB_OBJECTIVE_PTR 74 | #define TMB_OBJECTIVE_PTR this 75 | ``` 76 | For `ModelA.hpp`, `ModelB.hpp`, etc. similarly defined and in the current directory (`base::getwd()`), the R package containg them is created with: 77 | ```r 78 | TMBtools::tmb_create_package(path = "path/to/MyTMBPackage", 79 | tmb_files = c("ModelA.hpp", "ModelB.hpp")) 80 | ``` 81 | Once **MyTMBPackage** is installed, models can be accessed with: 82 | ```r 83 | library(MyTMBPackage) # package needs to be loaded 84 | 85 | # instantiate ModelA object 86 | modA <- TMB::MakeADFun(data = c(model = "ModelA", # which model to use 87 | data_list), 88 | parameters = param_list, 89 | DLL = "MyTMBPackage_TMBExports") # package's DLL 90 | 91 | modA$fn(other_param_list) # same usage as before 92 | 93 | # instantiate ModelB object 94 | modB <- TMB::MakeADFun(data = c(model = "ModelB", # use ModelB 95 | data_list_B), 96 | parameters = param_list_B, 97 | DLL = "MyTMBPackage_TMBExports") 98 | 99 | modB$fn(other_param_list_B) 100 | ``` 101 | 102 | For more usage details, e.g., how to add new models to an existing package, please see the package [vignette](http://htmlpreview.github.io/?https://github.com/mlysy/TMBtools/master/doc/TMBtools.html). 103 | 104 | ## Unit Tests 105 | 106 | As a sanity check, you may create a fully operational example package, i.e., with unit tests passing `R CMD --as-cran check`, with the sample code below. To run this code you will need to install the packages **devtools**, [**usethis**](https://CRAN.R-project.org/package=usethis), and [**numDeriv**](https://CRAN.R-project.org/package=numDeriv). 107 | ```r 108 | TMBtools::tmb_create_package(path = "path/to/TMBExampleTest", 109 | example_code = TRUE, 110 | fields = list( 111 | `Authors@R` = 'person("Your", "Name", 112 | email = "valid@email.com", 113 | role = c("aut", "cre"))')) 114 | 115 | # R wrapper functions to TMB models 116 | # note: data = list(pkg = ...) must match name of package (here TMBExampleTest) 117 | usethis::use_template(template = "norm_ADFun.R", package = "TMBtools", 118 | save_as = file.path("R", "norm_ADFun.R"), 119 | data = list(pkg = "TMBExampleTest")) 120 | usethis::use_template(template = "gamma_ADFun.R", package = "TMBtools", 121 | save_as = file.path("R", "gamma_ADFun.R"), 122 | data = list(pkg = "TMBExampleTest")) 123 | 124 | # testthat tests 125 | usethis::use_testthat() 126 | usethis::use_package(package = "numDeriv", type = "Suggests") 127 | usethis::use_template(template = "test-norm_ADFun.R", package = "TMBtools", 128 | save_as = file.path("tests", "testthat", 129 | "test-norm_ADFun.R")) 130 | usethis::use_template(template = "test-gamma_ADFun.R", package = "TMBtools", 131 | save_as = file.path("tests", "testthat", 132 | "test-gamma_ADFun.R")) 133 | 134 | # update NAMESPACE and package documentation 135 | pkgbuild::compile_dll() # need to compile src first 136 | devtools::document() 137 | ``` 138 | 139 | The last two lines set up all elements of the package, including the TMB C++ code, but without actually installing the package. The next few lines run the various package checks. **NOTE:** You must quit + restart R before running these to make sure things work properly on newer versions of R. 140 | 141 | ```r 142 | # essentially equivalent to R CMD --as-cran check 143 | devtools::check() # on your local platform 144 | 145 | # on winbuilder (CRAN's Windows) 146 | # must provide a valid email address 147 | devtools::check_win_devel() 148 | ``` 149 | 150 | ## **TMB** Coding Practices 151 | 152 | - **TMB** and other source code (e.g., [**Rcpp**]((http://www.rcpp.org/))) in an R package cannot be merged into a single shared library, as documented [here](https://github.com/kaskr/adcomp/issues/247). Therefore, the approach taken here is to have a separate shared object for the **TMB** models, for which the source code is stored in `src/TMB`, and for which separate compiling instructions provided in `Makevars[.win]`. 153 | 154 | Developers can include whatever **Rcpp** code they like in the package. The `Makevars[.win]` is set up so that R's normal C++ compiling is completely unaffected by the **TMB** part, and can be modified to provide e.g., additional `CXX_FLAGS` in the usual way. 155 | 156 | However, standard practice is that the name of the main shared library (the one that gets created by **Rcpp**) is that of the package, so the **TMB** shared object needs to be called something else. I have found that in order to avoid the CRAN check note [`Foreign function call to a different package`](https://stackoverflow.com/questions/24150185/foreign-function-calls-to-a-different-package-note), in the `NAMESPACE` file, it is necessary that *the `useDynLib` call to the main shared library come first*, i.e., before **TMB**'s. `TMBtools::tmb_create_package()` sets things up properly assuming that [roxygen2](https://CRAN.R-project.org/package=roxygen2/vignettes/roxygen2.html) is used to create the documentation, and `TMBtools::use_tmb()` provides instructions to do so when modifying the `NAMESPACE` is out of its control. 157 | 158 | - **TMBtools** follows the recommendations provided [here](https://github.com/kaskr/adcomp/issues/233) to combine all the package's **TMB** models into a single standalone-type meta-model `src/TMB/MyTMBPackage`. The appropriate model is selected at instantiation time using the `model` element of the `data` argument to `TMB::MakeADFun`. This results in much smaller package sizes compared to multiple standalone models, and doesn't appear to impact [performance](https://github.com/kaskr/adcomp/issues/247#issuecomment-473825191). 159 | 160 | - The meta-model implementation in **TMBtools** (based heavily on the approach advocated [here](https://github.com/kaskr/adcomp/issues/233#issuecomment-306032192)) is something like: 161 | 162 | ```c 163 | /// @file MyTMBPackage_TMBExports.cpp 164 | 165 | #include 166 | #include "ModelA.hpp" 167 | #include "ModelB.hpp" 168 | 169 | template 170 | Type objective_function::operator() () { 171 | DATA_STRING(model); 172 | if(model == "ModelA") { 173 | return ModelA(this); 174 | } else if(model == "ModelB") { 175 | return ModelB(this); 176 | } else { 177 | Rf_error("Unknown model."); 178 | } 179 | return 0; 180 | } 181 | ``` 182 | 183 | The unit tests in `TMBtools/test/testthat/test-aMb.R` indicate indicate that TMB does not get confused between `DATA_*` and `PARAMETER*` arguments across `.hpp` model files -- for example, `DATA_VECTOR(x)` in `ModelA` and `PARAMETER_MATRIX(x)` in `ModelB` -- nor does `TMB::MakeADFun` expect you to provide all arguments to all models at once. In other words, the main function bodies of `ModelA.hpp` and `ModelB.hpp` can be defined exactly you would for standalone files `ModelA.cpp` and `ModelB.cpp`. 184 | 185 | 186 | ## TODO 187 | 188 | - [ ] Add unit tests for `tmb_create_package()`, `use_tmb()`, and `export_models()`. 189 | - [ ] Run tests with `OpenMP` enabled. 190 | - [ ] Add examples for `use_tmb()` and `export_models()`. 191 | -------------------------------------------------------------------------------- /examples/tmb_create_package.R: -------------------------------------------------------------------------------- 1 | \dontrun{ 2 | # create package with example code 3 | tmb_create_package(path = "TMBTestPackage", 4 | example_code = TRUE) 5 | 6 | # the following steps will add R functions and tests 7 | # for which the resulting package will pass R CMD check --as-cran 8 | # need to have the following packages installed: 9 | # - devtools 10 | # - usethis 11 | # - numDeriv 12 | # run the following from within any of the TMBTestPackage subdfolders 13 | 14 | # wrapper functions to TMB models 15 | usethis::use_template(template = "norm_ADFun.R", package = "TMBtools", 16 | save_as = file.path("R", "norm_ADFun.R"), 17 | data = list(pkg = "TMBTestPackage")) 18 | usethis::use_template(template = "gamma_ADFun.R", package = "TMBtools", 19 | save_as = file.path("R", "gamma_ADFun.R"), 20 | data = list(pkg = "TMBTestPackage")) 21 | 22 | # testthat tests 23 | usethis::use_testthat() 24 | usethis::use_package(package = "numDeriv", type = "Suggests") 25 | usethis::use_template(template = "test-norm_ADFun.R", package = "TMBtools", 26 | save_as = file.path("tests", "testthat", 27 | "test-norm_ADFun.R")) 28 | usethis::use_template(template = "test-gamma_ADFun.R", package = "TMBtools", 29 | save_as = file.path("tests", "testthat", 30 | "test-gamma_ADFun.R")) 31 | 32 | # create roxygen documentation 33 | pkgbuild::compile_dll() # need to compile src first 34 | devtools::document() 35 | 36 | # essentially equivalent to R CMD check --as-cran 37 | devtools::check() 38 | } 39 | -------------------------------------------------------------------------------- /examples/tmb_package_skeleton.R: -------------------------------------------------------------------------------- 1 | \dontrun{ 2 | # create package with example code 3 | tmb_package_skeleton(name = "TMBTestPackage", example_code = TRUE) 4 | #' 5 | # for the following steps must have devtools package installed 6 | setwd("TMBTestPackage") 7 | # need to create shared library before running devtools::document() 8 | pkgbuild::compile_dll() 9 | devtools::document() 10 | # essentially equivalent to R CMD check --as-cran 11 | devtools::check() 12 | } 13 | -------------------------------------------------------------------------------- /inst/include/TMBtools/MatrixIP.hpp: -------------------------------------------------------------------------------- 1 | /// @file MatrixIP.hpp 2 | 3 | #ifndef MatrixIP_hpp 4 | #define MatrixIP_hpp 1 5 | 6 | /// Matrix-weighted inner product. 7 | /// 8 | /// For vectors `x` and `y` of length `n`, and `n x n` matrix `M`, calculates `x.transpose() * M * y`. 9 | /// @param[in] x First vector. 10 | /// @param[in] y Second vector. 11 | /// @param[in] M Weight matrix. 12 | /// @return `M`-weighted inner product between `x` and `y` (scalar). 13 | template 14 | Type MatrixIP(const vector& x, const vector& y, 15 | const matrix& M) { 16 | return (x.array() * (M * y).array()).sum(); 17 | } 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /inst/templates/GammaNLL.hpp: -------------------------------------------------------------------------------- 1 | /// @file GammaNLL.hpp 2 | 3 | #ifndef GammaNLL_hpp 4 | #define GammaNLL_hpp 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | 9 | // negative log-likelihood of the gamma distribution 10 | template 11 | Type GammaNLL(objective_function* obj) { 12 | DATA_VECTOR(x); // data vector 13 | PARAMETER(alpha); // shape parameter 14 | PARAMETER(beta); // scale parameter 15 | return -sum(dgamma(x, alpha, beta, true)); 16 | } 17 | 18 | #undef TMB_OBJECTIVE_PTR 19 | #define TMB_OBJECTIVE_PTR this 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /inst/templates/Makevars: -------------------------------------------------------------------------------- 1 | # --- TMB-specific Makevars file --- 2 | # 3 | # In principle, TMB model compilation is a completely separate process from 4 | # that of the remainder of 'src'. 5 | # Therefore, other Makevars flags can be added here, e.g., 6 | # 7 | ## CXX_STD = CXX14 # uncomment this line to enable C++14 support 8 | # 9 | # Flags specifically for the TMB compilation can also be set 10 | # through the 'TMB_FLAGS' argument below, e.g., 11 | # 12 | ## TMB_FLAGS = -I"../../inst/include" # add include directory inst/include 13 | # 14 | # --- TMB-specific compiling directives below --- 15 | 16 | .PHONY: all tmblib 17 | 18 | all: $(SHLIB) 19 | $(SHLIB): tmblib 20 | 21 | tmblib: 22 | (cd TMB; $(R_HOME)/bin$(R_ARCH_BIN)/Rscript \ 23 | --no-save --no-restore compile.R '$(TMB_FLAGS)') 24 | 25 | clean: 26 | rm -rf *.so *.o TMB/*.so TMB/*.o 27 | -------------------------------------------------------------------------------- /inst/templates/Makevars.win: -------------------------------------------------------------------------------- 1 | # --- TMB-specific Makevars file --- 2 | # 3 | # In principle, TMB model compilation is a completely separate process from 4 | # that of the remainder of 'src'. 5 | # Therefore, other Makevars flags can be added here, e.g., 6 | # 7 | ## CXX_STD = CXX14 # uncomment this line to enable C++14 support 8 | # 9 | # Flags specifically for the TMB compilation can also be set 10 | # through the 'TMB_FLAGS' argument below, e.g., 11 | # 12 | ## TMB_FLAGS = -I"../../inst/include" # add include directory inst/include 13 | # 14 | # --- TMB-specific compiling directives below --- 15 | 16 | .PHONY: all tmblib 17 | 18 | all: $(SHLIB) 19 | $(SHLIB): tmblib 20 | 21 | tmblib: 22 | (cd TMB; $(R_HOME)/bin$(R_ARCH_BIN)/Rscript \ 23 | --no-save --no-restore compile.R '$(TMB_FLAGS)') 24 | 25 | clean: 26 | rm -rf *.dll *.o TMB/*.dll TMB/*.o 27 | -------------------------------------------------------------------------------- /inst/templates/NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: fake comment so roxygen2 overwrites silently. 2 | exportPattern("^[[:alpha:]]+") 3 | {{usedl}} 4 | -------------------------------------------------------------------------------- /inst/templates/NormalNLL.hpp: -------------------------------------------------------------------------------- 1 | /// @file NormalNLL.hpp 2 | 3 | #ifndef NormalNLL_hpp 4 | #define NormalNLL_hpp 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | 9 | /// Negative log-likelihood of the normal distribution. 10 | template 11 | Type NormalNLL(objective_function* obj) { 12 | DATA_VECTOR(x); // data vector 13 | PARAMETER(mu); // mean parameter 14 | PARAMETER(sigma); // standard deviation parameter 15 | return -sum(dnorm(x,mu,sigma,true)); // negative log likelihood 16 | } 17 | 18 | #undef TMB_OBJECTIVE_PTR 19 | #define TMB_OBJECTIVE_PTR this 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /inst/templates/TMBExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by TMBtools: do not edit by hand 2 | 3 | #define TMB_LIB_INIT R_init_{{pkg}}_TMBExports 4 | #include 5 | {{{includes}}} 6 | 7 | template 8 | Type objective_function::operator() () { 9 | DATA_STRING(model); 10 | {{{switches}}} 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /inst/templates/compile.R: -------------------------------------------------------------------------------- 1 | tmb_name <- "{{pkg}}_TMBExports" 2 | tmb_flags <- commandArgs(trailingOnly = TRUE) 3 | 4 | if(file.exists(paste0(tmb_name, ".cpp"))) { 5 | if(length(tmb_flags) == 0) tmb_flags <- "" 6 | TMB::compile(file = paste0(tmb_name, ".cpp"), 7 | PKG_CXXFLAGS = tmb_flags, 8 | safebounds = FALSE, safeunload = FALSE) 9 | file.copy(from = paste0(tmb_name, .Platform$dynlib.ext), 10 | to = "..", overwrite = TRUE) 11 | } 12 | 13 | # cleanup done in ../Makevars[.win] 14 | -------------------------------------------------------------------------------- /inst/templates/gamma_ADFun.R: -------------------------------------------------------------------------------- 1 | #' Create a \code{TMB::ADFun} object for the gamma likelihood. 2 | #' 3 | #' @param x Vector of observations. 4 | #' @return A list as returned by \code{TMB::MakeADFun} representing the negative loglikelihood of a gamma distribution. 5 | #' @export 6 | gamma_ADFun <- function(x) { 7 | TMB::MakeADFun(data = list(model = "GammaNLL", x = x), 8 | parameters = list(alpha = 1, beta = 1), 9 | DLL = "{{pkg}}_TMBExports", silent = TRUE) 10 | } 11 | -------------------------------------------------------------------------------- /inst/templates/init_dummy_file.cpp: -------------------------------------------------------------------------------- 1 | // Dummy file required so that {{usedl}} doesn't fail on empty 'src' 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | void attribute_visible R_init_{{pkg}}(DllInfo *dll) { 8 | R_registerRoutines(dll, NULL, NULL, NULL, NULL); 9 | R_useDynamicSymbols(dll, FALSE); 10 | } 11 | -------------------------------------------------------------------------------- /inst/templates/norm_ADFun.R: -------------------------------------------------------------------------------- 1 | #' Create a \code{TMB::ADFun} object for the normal likelihood. 2 | #' 3 | #' @param x Vector of observations. 4 | #' @return A list as returned by \code{TMB::MakeADFun} representing the negative loglikelihood of a univariate normal. 5 | #' @export 6 | norm_ADFun <- function(x) { 7 | TMB::MakeADFun(data = list(model = "NormalNLL", x = x), 8 | parameters = list(mu = 0, sigma = 1), 9 | DLL = "{{pkg}}_TMBExports", silent = TRUE) 10 | } 11 | -------------------------------------------------------------------------------- /inst/templates/old/DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: @@PKG@@ 2 | Type: Package 3 | Title: What the package does (short line) 4 | Version: 0.0.0.9000 5 | Date: 2019-03-29 6 | Author: Who wrote it 7 | Maintainer: Who to complain to 8 | Description: More about what it does (maybe more than one line) 9 | LinkingTo: TMB 10 | License: GPL (>=2) 11 | Encoding: UTF-8 12 | -------------------------------------------------------------------------------- /inst/templates/old/Read_and_delete_me: -------------------------------------------------------------------------------- 1 | * Edit the help file skeletons in 'man', possibly combining help files 2 | for multiple functions. 3 | * Edit the exports in 'NAMESPACE', and add necessary imports. 4 | * Put any C/C++/Fortran code in 'src'. 5 | * If you have compiled code, add a useDynLib() directive to 6 | 'NAMESPACE'. 7 | * Run R CMD build to build the package tarball. 8 | * Run R CMD check to check the package tarball. 9 | 10 | Read "Writing R Extensions" for more information. 11 | 12 | --- Additional TMB-specific notes --- 13 | 14 | * @@use_Rcpp@@Added placeholder file 'src/init_dummy_file.cpp' to avoid problems with empty 'src'. 15 | You _must_ delete this file once any C/C++ source files are added to the package. 16 | 17 | * '@@usedl_pkg@@' _must_ preceed 18 | '@@usedl_tmb@@' in 'NAMESPACE' file. 19 | 20 | With 'roxygen2' this is achieved with: 21 | 22 | @rawNamespace @@usedl_pkg@@; @@usedl_tmb@@ 23 | -------------------------------------------------------------------------------- /inst/templates/old/tmb_examples.R: -------------------------------------------------------------------------------- 1 | #' Example of using \pkg{TMB} in a package. 2 | #' 3 | #' This function is an \R wrapper to the univariate normal \pkg{TMB} model found in \code{src/TMB/NormNLL.hpp}. 4 | #' 5 | #' @param x Numeric vector of observations. 6 | #' @return A list as returned by \code{TMB::MakeADFun}. 7 | #' @export 8 | norm_ADFun <- function(x) { 9 | if(!is.numeric(x)) stop("x must be a numeric vector.") 10 | TMB::MakeADFun(data = list(model_name = "NormNLL", x = x), 11 | DLL = "@@pkg@@_TMBExports", 12 | parameters = list(mu = 0, sigma = 1), silent = TRUE) 13 | } 14 | -------------------------------------------------------------------------------- /inst/templates/package.R: -------------------------------------------------------------------------------- 1 | #' @rawNamespace {{usedl}} 2 | #' @keywords internal 3 | "_PACKAGE" 4 | 5 | # The following block is used by usethis to automatically manage 6 | # roxygen namespace tags. Modify with care! 7 | ## usethis namespace: start 8 | ## usethis namespace: end 9 | NULL 10 | -------------------------------------------------------------------------------- /inst/templates/test-gamma_ADFun.R: -------------------------------------------------------------------------------- 1 | 2 | context("gamma_ADFun") 3 | 4 | test_that("gamma_ADFun calculates correct negloglik, gradient, and hessian", { 5 | nll_fun <- function(theta, y) { 6 | -sum(dgamma(x = y, shape = theta[1], scale = theta[2], log = TRUE)) 7 | } 8 | nreps <- 20 9 | for(ii in 1:nreps) { 10 | # simulate data/parameters 11 | n <- sample(10:100, 1) 12 | x <- rexp(n) 13 | theta <- c(alpha = rexp(1), beta = rexp(1)) 14 | # nll/g/h with R + numDeriv 15 | ll1 <- nll_fun(theta, x) 16 | gg1 <- numDeriv::grad(func = nll_fun, x = theta, y = x) 17 | hh1 <- numDeriv::hessian(func = nll_fun, x = theta, y = x) 18 | # nll/g/h with TMB 19 | nll_obj <- gamma_ADFun(x) 20 | ll2 <- nll_obj$fn(theta) 21 | gg2 <- nll_obj$gr(theta)[1,] 22 | hh2 <- nll_obj$he(theta) 23 | # check they are identical 24 | expect_equal(ll1, ll2) 25 | expect_equal(gg1, gg2) 26 | expect_equal(hh1, hh2) 27 | } 28 | }) 29 | -------------------------------------------------------------------------------- /inst/templates/test-norm_ADFun.R: -------------------------------------------------------------------------------- 1 | 2 | context("norm_ADFun") 3 | 4 | 5 | test_that("norm_ADFun calculates correct negloglik, gradient, and hessian", { 6 | nll_fun <- function(theta, y) { 7 | -sum(dnorm(x = x, mean = theta[1], sd = theta[2], log = TRUE)) 8 | } 9 | nreps <- 20 10 | for(ii in 1:nreps) { 11 | # simulate data/parameters 12 | n <- sample(10:100, 1) 13 | x <- rnorm(n) 14 | theta <- c(mu = rnorm(1), sigma = rexp(1)) 15 | # nll/g/h/ with R + numDeriv 16 | ll1 <- nll_fun(theta, x) 17 | gg1 <- numDeriv::grad(func = nll_fun, x = theta, y = x) 18 | hh1 <- numDeriv::hessian(func = nll_fun, x = theta, y = x) 19 | # nll/g/h with TMB 20 | nll_obj <- norm_ADFun(x) 21 | ll2 <- nll_obj$fn(theta) 22 | gg2 <- nll_obj$gr(theta)[1,] 23 | hh2 <- nll_obj$he(theta) 24 | # check they are identical 25 | expect_equal(ll1, ll2) 26 | expect_equal(gg1, gg2) 27 | expect_equal(hh1, hh2) 28 | } 29 | }) 30 | -------------------------------------------------------------------------------- /man/TMBtools-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/TMBtools-package.R 3 | \docType{package} 4 | \name{TMBtools-package} 5 | \alias{TMBtools} 6 | \alias{TMBtools-package} 7 | \title{Tools for developing \R packages interfacing with \pkg{TMB}.} 8 | \description{ 9 | Provides helper functions for creating packages which contain 'TMB' source code. 10 | } 11 | \details{ 12 | Currently, the packages provides two main functions \code{\link{tmb_create_package}} and \code{\link{export_models}}, for creating packages containing \pkg{TMB} source code, and updating the package's compile instructions when new \pkg{TMB} models are added. Please see walkthrough in \code{vignette(p = "TMBtools")}. 13 | } 14 | \author{ 15 | \strong{Maintainer}: Martin Lysy \email{mlysy@uwaterloo.ca} 16 | 17 | } 18 | -------------------------------------------------------------------------------- /man/export_models.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/export_models.R 3 | \name{export_models} 4 | \alias{export_models} 5 | \title{Create C++ code to export \pkg{TMB} models from package.} 6 | \usage{ 7 | export_models(pkg = ".") 8 | } 9 | \arguments{ 10 | \item{pkg}{Character string: any subdirectory of the package source code.} 11 | } 12 | \value{ 13 | Invisible; called for its side effects. 14 | } 15 | \description{ 16 | Create C++ code to export \pkg{TMB} models from package. 17 | } 18 | \details{ 19 | \pkg{TMB} models should be saved as C++ header files of the form \code{src/TMB/*.hpp}, and written almost exactly as with usual \pkg{TMB} \code{*.cpp} models. So for example, \code{src/TMB/ModelA.hpp} would be written as: 20 | \preformatted{ 21 | // __DO NOT__ '#include ' as file is not include-guarded 22 | 23 | #undef TMB_OBJECTIVE_PTR 24 | #define TMB_OBJECTIVE_PTR obj 25 | 26 | // name of function _must_ match file name (ModelA) 27 | template 28 | Type ModelA(objective_function* obj) { 29 | 30 | // _exactly_ the same code as for usual 'ModelA.cpp' 31 | 32 | } 33 | 34 | #undef TMB_OBJECTIVE_PTR 35 | #define TMB_OBJECTIVE_PTR this 36 | } 37 | The function \code{export_models} creates a file \code{src/TMB/pkgname_TMBExports.cpp} containing a single \pkg{TMB} model object which dispatches the appropriate \code{ModelA.hpp}, \code{ModelB.hpp}, etc. using \code{if/else} statements. At the \R level, the correct model is invoked from \code{TMB::MakeADFun} exactly as for a single \pkg{TMB} model, except the \code{data} list argument gets an additional element \code{model} specifying the name of the model, e.g., \code{model = "ModelA"}. 38 | 39 | \code{export_models} assumes that each file of the form \code{src/TMB/*.hpp} contains \emph{exactly one} \pkg{TMB} model. In order for these to \code{#include} additional \code{.hpp} files, these additional files must be placed either in a subfolder of \code{src/TMB}, or in (a subfolder of) \code{inst/include}. The advantage of the latter approach is that the additional files are available to other \R packages via \code{LinkingTo: pkgname} is the other package's \code{DESCRIPTION}. If the latter approach is used, the \code{TMB} compiler must be notified of the additional include directory. This is done by setting the \code{TMB_FLAGS} in \code{src/Makevars[.win]} to 40 | \preformatted{ 41 | TMB_FLAGS = -I"../../inst/include" 42 | } 43 | Other flags specific to the \pkg{TMB} compiler can be set here as well, as can the usual \code{CXX_FLAGS}, etc. for other source code in \code{src}, which is compiled independently of that in \pkg{src/TMB}. 44 | } 45 | \seealso{ 46 | \code{\link{use_tmb}} 47 | } 48 | -------------------------------------------------------------------------------- /man/gamma_ADFun.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/gamma_ADFun.R 3 | \name{gamma_ADFun} 4 | \alias{gamma_ADFun} 5 | \title{Create a \code{TMB::ADFun} object for the gamma likelihood.} 6 | \usage{ 7 | gamma_ADFun(x) 8 | } 9 | \arguments{ 10 | \item{x}{Vector of observations.} 11 | } 12 | \value{ 13 | A list as returned by \code{TMB::MakeADFun} representing the negative loglikelihood of a gamma distribution. 14 | } 15 | \description{ 16 | Create a \code{TMB::ADFun} object for the gamma likelihood. 17 | } 18 | -------------------------------------------------------------------------------- /man/hadamard.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/hadamard.R 3 | \name{hadamard} 4 | \alias{hadamard} 5 | \title{Calculate the Hadamard product between two matrices.} 6 | \usage{ 7 | hadamard(A, B) 8 | } 9 | \arguments{ 10 | \item{A}{First matrix.} 11 | 12 | \item{B}{Second matrix of same dimensions as \code{A}.} 13 | } 14 | \value{ 15 | Elementwise product between the two matices. 16 | } 17 | \description{ 18 | Commonly referred to as elementwise matrix multiplication. 19 | } 20 | -------------------------------------------------------------------------------- /man/norm_ADFun.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/norm_ADFun.R 3 | \name{norm_ADFun} 4 | \alias{norm_ADFun} 5 | \title{Create a \code{TMB::ADFun} object for the normal likelihood.} 6 | \usage{ 7 | norm_ADFun(x) 8 | } 9 | \arguments{ 10 | \item{x}{Vector of observations.} 11 | } 12 | \value{ 13 | A list as returned by \code{TMB::MakeADFun} representing the negative loglikelihood of a univariate normal. 14 | } 15 | \description{ 16 | Create a \code{TMB::ADFun} object for the normal likelihood. 17 | } 18 | -------------------------------------------------------------------------------- /man/tmb_create_package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/tmb_create_package.R 3 | \name{tmb_create_package} 4 | \alias{tmb_create_package} 5 | \title{Create a \pkg{TMB} package.} 6 | \usage{ 7 | tmb_create_package( 8 | path, 9 | tmb_files = character(), 10 | fields = NULL, 11 | open = interactive(), 12 | example_code = FALSE 13 | ) 14 | } 15 | \arguments{ 16 | \item{path}{Absolute or relative path to where the package is to be created. If the path exists, it is used. If it does not exist, it is created, provided that the parent path exists.} 17 | 18 | \item{tmb_files}{Optional character vector of \pkg{TMB} header files to include in the package. See \strong{Details}.} 19 | 20 | \item{fields, open}{Same function as corresponding arguments in \code{usethis::create_package}.} 21 | 22 | \item{example_code}{Adds example \pkg{TMB} files to the package (see \strong{Examples}).} 23 | } 24 | \value{ 25 | Nothing; called for its side effect. 26 | } 27 | \description{ 28 | Create a \pkg{TMB} package. 29 | } 30 | \details{ 31 | Calls \code{usethis::create_package} followed by \code{\link{use_tmb}} and \code{\link{export_models}}, which add the \pkg{TMB} infrastructure and initialize the provided \pkg{TMB} model list, respectively. Please see documentation for these functions as to how exactly a \pkg{TMB}-enabled package should be set up. 32 | } 33 | \examples{ 34 | \dontrun{ 35 | # create package with example code 36 | tmb_create_package(path = "TMBTestPackage", 37 | example_code = TRUE) 38 | 39 | # the following steps will add R functions and tests 40 | # for which the resulting package will pass R CMD check --as-cran 41 | # need to have the following packages installed: 42 | # - devtools 43 | # - usethis 44 | # - numDeriv 45 | # run the following from within any of the TMBTestPackage subdfolders 46 | 47 | # wrapper functions to TMB models 48 | usethis::use_template(template = "norm_ADFun.R", package = "TMBtools", 49 | save_as = file.path("R", "norm_ADFun.R"), 50 | data = list(pkg = "TMBTestPackage")) 51 | usethis::use_template(template = "gamma_ADFun.R", package = "TMBtools", 52 | save_as = file.path("R", "gamma_ADFun.R"), 53 | data = list(pkg = "TMBTestPackage")) 54 | 55 | # testthat tests 56 | usethis::use_testthat() 57 | usethis::use_package(package = "numDeriv", type = "Suggests") 58 | usethis::use_template(template = "test-norm_ADFun.R", package = "TMBtools", 59 | save_as = file.path("tests", "testthat", 60 | "test-norm_ADFun.R")) 61 | usethis::use_template(template = "test-gamma_ADFun.R", package = "TMBtools", 62 | save_as = file.path("tests", "testthat", 63 | "test-gamma_ADFun.R")) 64 | 65 | # create roxygen documentation 66 | pkgbuild::compile_dll() # need to compile src first 67 | devtools::document() 68 | 69 | # essentially equivalent to R CMD check --as-cran 70 | devtools::check() 71 | } 72 | } 73 | \seealso{ 74 | \code{\link{use_tmb}} for adding \pkg{TMB} infrastructure to an existing package,\code{\link{export_models}} for adding \pkg{TMB} model files after the package is created. 75 | } 76 | -------------------------------------------------------------------------------- /man/use_tmb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/use_tmb.R 3 | \name{use_tmb} 4 | \alias{use_tmb} 5 | \title{Add \pkg{TMB} functionality to an existing package.} 6 | \usage{ 7 | use_tmb() 8 | } 9 | \value{ 10 | Nothing; called for its side effects. 11 | } 12 | \description{ 13 | Add \pkg{TMB} functionality to an existing package. 14 | } 15 | \details{ 16 | Adds the following to the package: 17 | 18 | \itemize{ 19 | \item \code{src/TMB/compile.R}: runs the C++ compiler on \pkg{TMB} model files (see \code{\link{export_models}}). 20 | \item \code{src/Makevars[.win]}: ensures that \pkg{TMB} compilation does not affect that of other source files in \code{src}. 21 | \item \code{src/init_dummy_file.cpp}: needed to set \code{R_registerRoutines} if the package contains no other source code apart from what's in \code{src/TMB}. 22 | \item \code{Imports: TMB} and \code{LinkingTo: TMB} are added to the package's \code{DESCRIPTION}. 23 | \item An optional file \code{R/pkgname-package.R} with \pkg{roxygen2} \code{NAMESPACE} directives, if such a file does not exist. Otherwise, prints instructions as to how the \code{NAMESPACE} must be modified (see below). 24 | } 25 | 26 | Because of how \pkg{TMB} source files are compiled, at present the package must create two shared object (\code{.so}, \code{.dll}) files: \code{pkgname_TMBExports.so} for the \pkg{TMB} models, and \code{pkgname.so} for the usual package source code. In the \code{NAMESPACE} file, it is imperative that the latter be `useDynLib`ed before the former. The fail-safe \pkg{roxygen2} instruction for this is 27 | \preformatted{ 28 | #' @rawNamespace useDynLib(pkgname, .registration = TRUE); useDynLib(pkgname_TMBExports) 29 | } 30 | } 31 | \seealso{ 32 | \code{\link{export_models}} for details on adding \pkg{TMB} model files after running \code{use_tmb}. 33 | } 34 | -------------------------------------------------------------------------------- /src/Hadamard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace Rcpp; 3 | 4 | // Elementwise multiplication of two matrices, i.e., Hadamard product. 5 | // [[Rcpp::export(".hadamard")]] 6 | SEXP hadamard(NumericMatrix A, NumericMatrix B) { 7 | NumericVector C = A * B; 8 | C.attr("dim") = Dimension(A.nrow(), B.ncol()); 9 | return C; 10 | } 11 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | # --- TMB-specific Makevars file --- 2 | # 3 | # In principle, TMB model compilation is a completely separate process from 4 | # that of the remainder of 'src'. 5 | # Therefore, other Makevars flags can be added here, e.g., 6 | # 7 | ## CXX_STD = CXX14 # uncomment this line to enable C++14 support 8 | # 9 | # Flags specifically for the TMB compilation can also be set 10 | # through the 'TMB_FLAGS' argument below, e.g., 11 | # 12 | TMB_FLAGS = -I"../../inst/include" # add include directory inst/include 13 | # 14 | # --- TMB-specific compiling directives below --- 15 | 16 | .PHONY: all tmblib 17 | 18 | all: $(SHLIB) 19 | $(SHLIB): tmblib 20 | 21 | tmblib: 22 | (cd TMB; $(R_HOME)/bin$(R_ARCH_BIN)/Rscript --no-save --no-restore compile.R '$(TMB_FLAGS)') 23 | 24 | clean: 25 | rm -rf *.so *.o TMB/*.so TMB/*.o 26 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | # --- TMB-specific Makevars file --- 2 | # 3 | # In principle, TMB model compilation is a completely separate process from 4 | # that of the remainder of 'src'. 5 | # Therefore, other Makevars flags can be added here, e.g., 6 | # 7 | ## CXX_STD = CXX14 # uncomment this line to enable C++14 support 8 | # 9 | # Flags specifically for the TMB compilation can also be set 10 | # through the 'TMB_FLAGS' argument below, e.g., 11 | # 12 | TMB_FLAGS = -I"../../inst/include" # add include directory inst/include 13 | # 14 | # --- TMB-specific compiling directives below --- 15 | 16 | .PHONY: all tmblib 17 | 18 | all: $(SHLIB) 19 | $(SHLIB): tmblib 20 | 21 | tmblib: 22 | (cd TMB; $(R_HOME)/bin$(R_ARCH_BIN)/Rscript --no-save --no-restore compile.R '$(TMB_FLAGS)') 23 | 24 | clean: 25 | rm -rf *.dll *.o TMB/*.dll TMB/*.o 26 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 9 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 10 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 11 | #endif 12 | 13 | // hadamard 14 | SEXP hadamard(NumericMatrix A, NumericMatrix B); 15 | RcppExport SEXP _TMBtools_hadamard(SEXP ASEXP, SEXP BSEXP) { 16 | BEGIN_RCPP 17 | Rcpp::RObject rcpp_result_gen; 18 | Rcpp::RNGScope rcpp_rngScope_gen; 19 | Rcpp::traits::input_parameter< NumericMatrix >::type A(ASEXP); 20 | Rcpp::traits::input_parameter< NumericMatrix >::type B(BSEXP); 21 | rcpp_result_gen = Rcpp::wrap(hadamard(A, B)); 22 | return rcpp_result_gen; 23 | END_RCPP 24 | } 25 | 26 | static const R_CallMethodDef CallEntries[] = { 27 | {"_TMBtools_hadamard", (DL_FUNC) &_TMBtools_hadamard, 2}, 28 | {NULL, NULL, 0} 29 | }; 30 | 31 | RcppExport void R_init_TMBtools(DllInfo *dll) { 32 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 33 | R_useDynamicSymbols(dll, FALSE); 34 | } 35 | -------------------------------------------------------------------------------- /src/TMB/GammaNLL.hpp: -------------------------------------------------------------------------------- 1 | /// @file GammaNLL.hpp 2 | 3 | #ifndef GammaNLL_hpp 4 | #define GammaNLL_hpp 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | 9 | // negative log-likelihood of the gamma distribution 10 | template 11 | Type GammaNLL(objective_function* obj) { 12 | DATA_VECTOR(x); // data vector 13 | PARAMETER(alpha); // shape parameter 14 | PARAMETER(beta); // scale parameter 15 | return -sum(dgamma(x, alpha, beta, true)); 16 | } 17 | 18 | #undef TMB_OBJECTIVE_PTR 19 | #define TMB_OBJECTIVE_PTR this 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /src/TMB/NormalNLL.hpp: -------------------------------------------------------------------------------- 1 | /// @file NormalNLL.hpp 2 | 3 | #ifndef NormalNLL_hpp 4 | #define NormalNLL_hpp 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | 9 | /// Negative log-likelihood of the normal distribution. 10 | template 11 | Type NormalNLL(objective_function* obj) { 12 | DATA_VECTOR(x); // data vector 13 | PARAMETER(mu); // mean parameter 14 | PARAMETER(sigma); // standard deviation parameter 15 | return -sum(dnorm(x,mu,sigma,true)); // negative log likelihood 16 | } 17 | 18 | #undef TMB_OBJECTIVE_PTR 19 | #define TMB_OBJECTIVE_PTR this 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /src/TMB/Rxz_dpd.hpp: -------------------------------------------------------------------------------- 1 | #ifndef Rxz_dpd_hpp 2 | #define Rxz_dpd_hpp 1 3 | 4 | #include "TMBtools/MatrixIP.hpp" 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | template 9 | Type Rxz_dpd(objective_function* obj) { 10 | DATA_VECTOR(R); 11 | DATA_VECTOR(z); 12 | PARAMETER_MATRIX(x); 13 | return MatrixIP(R, z, x); 14 | } 15 | #undef TMB_OBJECTIVE_PTR 16 | #define TMB_OBJECTIVE_PTR this 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /src/TMB/TMBtools_TMBExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by TMBtools: do not edit by hand 2 | 3 | #define TMB_LIB_INIT R_init_TMBtools_TMBExports 4 | #include 5 | #include "GammaNLL.hpp" 6 | #include "NormalNLL.hpp" 7 | #include "Rxz_dpd.hpp" 8 | #include "xRy_dpd.hpp" 9 | #include "xRy_pdp.hpp" 10 | #include "xRz_pdd.hpp" 11 | #include "ySx_pdp.hpp" 12 | 13 | template 14 | Type objective_function::operator() () { 15 | DATA_STRING(model); 16 | if(model == "GammaNLL") { 17 | return GammaNLL(this); 18 | } else if(model == "NormalNLL") { 19 | return NormalNLL(this); 20 | } else if(model == "Rxz_dpd") { 21 | return Rxz_dpd(this); 22 | } else if(model == "xRy_dpd") { 23 | return xRy_dpd(this); 24 | } else if(model == "xRy_pdp") { 25 | return xRy_pdp(this); 26 | } else if(model == "xRz_pdd") { 27 | return xRz_pdd(this); 28 | } else if(model == "ySx_pdp") { 29 | return ySx_pdp(this); 30 | } else { 31 | Rf_error("Unknown model."); 32 | } 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/TMB/compile.R: -------------------------------------------------------------------------------- 1 | tmb_flags <- commandArgs(trailingOnly = TRUE) 2 | if(length(tmb_flags) == 0) tmb_flags <- "" 3 | 4 | ## if(length(Sys.glob("*.cpp")) > 0) { 5 | ## # compile tmb models 6 | ## invisible(sapply(Sys.glob("*.cpp"), 7 | ## TMB::compile, PKG_CXXFLAGS = tmb_flags, 8 | ## safebounds = FALSE, safeunload = FALSE)) 9 | ## # copy dynlibs to src 10 | ## invisible(file.copy(from = Sys.glob(paste0("*", .Platform$dynlib.ext)), 11 | ## to = "..", overwrite = TRUE)) 12 | ## } 13 | 14 | tmb_name <- "TMBtools_TMBExports" 15 | if(file.exists(paste0(tmb_name, ".cpp"))) { 16 | TMB::compile(file = paste0(tmb_name, ".cpp"), 17 | PKG_CXXFLAGS = tmb_flags, 18 | safebounds = FALSE, safeunload = FALSE) 19 | file.copy(from = paste0(tmb_name, .Platform$dynlib.ext), 20 | to = "..", overwrite = TRUE) 21 | } 22 | 23 | # cleanup done in ../Makevars[.win] 24 | -------------------------------------------------------------------------------- /src/TMB/xRy_dpd.hpp: -------------------------------------------------------------------------------- 1 | #ifndef xRy_dpd_hpp 2 | #define xRy_dpd_hpp 1 3 | 4 | #include "TMBtools/MatrixIP.hpp" 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | template 9 | Type xRy_dpd(objective_function* obj) { 10 | DATA_VECTOR(x); 11 | DATA_VECTOR(y); 12 | PARAMETER_MATRIX(R); 13 | return MatrixIP(x, y, R); 14 | } 15 | #undef TMB_OBJECTIVE_PTR 16 | #define TMB_OBJECTIVE_PTR this 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /src/TMB/xRy_pdp.hpp: -------------------------------------------------------------------------------- 1 | #ifndef xRy_pdp_hpp 2 | #define xRy_pdp_hpp 1 3 | 4 | #include "TMBtools/MatrixIP.hpp" 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | template 9 | Type xRy_pdp(objective_function* obj) { 10 | PARAMETER_VECTOR(x); 11 | PARAMETER_VECTOR(y); 12 | DATA_MATRIX(R); 13 | return MatrixIP(x, y, R); 14 | } 15 | #undef TMB_OBJECTIVE_PTR 16 | #define TMB_OBJECTIVE_PTR this 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /src/TMB/xRz_pdd.hpp: -------------------------------------------------------------------------------- 1 | #ifndef xRz_pdd_hpp 2 | #define xRz_pdd_hpp 1 3 | 4 | #include "TMBtools/MatrixIP.hpp" 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | template 9 | Type xRz_pdd(objective_function* obj) { 10 | PARAMETER_VECTOR(x); 11 | DATA_VECTOR(z); 12 | DATA_MATRIX(R); 13 | return MatrixIP(x, z, R); 14 | } 15 | #undef TMB_OBJECTIVE_PTR 16 | #define TMB_OBJECTIVE_PTR this 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /src/TMB/ySx_pdp.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ySx_pdp_hpp 2 | #define ySx_pdp_hpp 1 3 | 4 | #include "TMBtools/MatrixIP.hpp" 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | template 9 | Type ySx_pdp(objective_function* obj) { 10 | PARAMETER_VECTOR(y); 11 | PARAMETER_VECTOR(x); 12 | DATA_MATRIX(S); 13 | return MatrixIP(y, x, S); 14 | } 15 | #undef TMB_OBJECTIVE_PTR 16 | #define TMB_OBJECTIVE_PTR this 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(TMBtools) 3 | 4 | test_check("TMBtools") 5 | -------------------------------------------------------------------------------- /tests/testthat/old/test-lm_eigen.R: -------------------------------------------------------------------------------- 1 | 2 | context("lm_eigen") 3 | 4 | test_that("lm_eigen calculates correct regression output", { 5 | nreps <- 20 6 | for(ii in 1:nreps) { 7 | n <- sample(10:100, 1) 8 | p <- sample(3:6,1) 9 | X <- matrix(rnorm(n*p), n, p) 10 | y <- rnorm(n) 11 | M <- lm(y ~ X - 1) 12 | M2 <- lm_eigen(y, X) 13 | rownames(M2$vcov) <- colnames(M2$vcov) <- names(M2$coef) <- names(coef(M)) 14 | expect_equal(coef(M), M2$coef) 15 | expect_equal(vcov(M), M2$vcov) 16 | expect_equal(sigma(M), M2$sigma) 17 | } 18 | }) 19 | -------------------------------------------------------------------------------- /tests/testthat/test-aMb.R: -------------------------------------------------------------------------------- 1 | 2 | context("matrix-weighted inner products") 3 | 4 | sim_a <- function(n) rnorm(n) 5 | sim_b <- function(n) rnorm(n) 6 | sim_M <- function(n) matrix(rnorm(n^2), n, n) 7 | 8 | # R functions 9 | aMb2vec <- function(a, M, b) c(a, M, b) 10 | vec2aMb <- function(vec) { 11 | n <- -1 + sqrt(1+length(vec)) 12 | list(a = vec[1:n], M = matrix(vec[n+1:(n^2)], n, n), 13 | b = vec[n+n^2+1:n]) 14 | } 15 | aMb_fun <- function(a, M, b) sum(a * (M %*% b)) 16 | aMb_fun_pd <- function(x, a, M, b, n) { 17 | if(missing(a)) { 18 | a <- x[1:n] 19 | x <- x[-(1:n)] 20 | } 21 | if(missing(M)) { 22 | M <- matrix(x[1:n^2], n, n) 23 | x <- x[-(1:n^2)] 24 | } 25 | if(missing(b)) { 26 | b <- x[1:n] 27 | } 28 | aMb_fun(a, M, b) 29 | } 30 | 31 | # lists to use for do.call 32 | get_dclists <- function(hname, a, M, b, n) { 33 | # parse header name 34 | tmp <- strsplit(hname, split = "")[[1]] 35 | vnames <- tmp[1:3] 36 | vtypes <- tmp[5:7] 37 | # variable list 38 | vlist <- list(a, M, b) 39 | names(vlist) <- vnames 40 | # MakeADFun::data 41 | odata <- vlist[vtypes == "d"] 42 | # R::data 43 | fdata <- setNames(vlist, c("a", "M", "b")) 44 | # MakeADFun::params 45 | plist <- list(sim_a(n), sim_M(n), sim_b(n)) 46 | names(plist) <- vnames 47 | opars <- plist[vtypes == "p"] 48 | # R grad/hess 49 | ghlist <- c(list(x = unlist(vlist[vtypes == "p"], use.names = FALSE)), 50 | fdata[vtypes == "d"]) 51 | list(data = c(model = hname, odata), parameters = opars, 52 | nl = fdata, gh = ghlist, ad = vlist[vtypes == "p"]) 53 | } 54 | 55 | hnames <- c("xRy_dpd", "Rxz_dpd", "xRz_pdd", "xRy_pdp", "ySx_pdp") 56 | 57 | for(hname in hnames) { 58 | test_that(paste0(hname, 59 | " calculates negloglik, gradient, and hessian correctly"), { 60 | nreps <- 20 61 | for(ii in 1:nreps) { 62 | n <- sample(2:5,1) 63 | a <- sim_a(n) 64 | b <- sim_b(n) 65 | M <- sim_M(n) 66 | dcl <- get_dclists(hname, a, M, b, n) 67 | aMb_obj <- TMB::MakeADFun(data = dcl$data, 68 | parameters = dcl$parameters, 69 | DLL = "TMBtools_TMBExports", silent = TRUE) 70 | # in R 71 | ll1 <- do.call(aMb_fun, dcl$nl) 72 | gg1 <- do.call(numDeriv::grad, c(func = aMb_fun_pd, dcl$gh, n = n)) 73 | hh1 <- do.call(numDeriv::hessian, c(func = aMb_fun_pd, dcl$gh, n = n)) 74 | # in TMB 75 | ll2 <- aMb_obj$fn(unlist(dcl$ad, use.names = FALSE)) 76 | gg2 <- aMb_obj$gr(unlist(dcl$ad, use.names = FALSE))[1,] 77 | hh2 <- aMb_obj$he(unlist(dcl$ad, use.names = FALSE)) 78 | expect_equal(ll1, ll2, tolerance = 1e-6) 79 | expect_equal(gg1, gg2, tolerance = 1e-6) 80 | expect_equal(hh1, hh2, tolerance = 1e-6) 81 | } 82 | }) 83 | } 84 | -------------------------------------------------------------------------------- /tests/testthat/test-gamma_ADFun.R: -------------------------------------------------------------------------------- 1 | 2 | context("gamma_ADFun") 3 | 4 | test_that("gamma_ADFun calculates correct negloglik, gradient, and hessian", { 5 | nll_fun <- function(theta, y) { 6 | -sum(dgamma(x = y, shape = theta[1], scale = theta[2], log = TRUE)) 7 | } 8 | nreps <- 20 9 | for(ii in 1:nreps) { 10 | # simulate data/parameters 11 | n <- sample(10:100, 1) 12 | x <- rexp(n) 13 | theta <- c(alpha = rexp(1), beta = rexp(1)) 14 | # nll/g/h with R + numDeriv 15 | ll1 <- nll_fun(theta, x) 16 | gg1 <- numDeriv::grad(func = nll_fun, x = theta, y = x) 17 | hh1 <- numDeriv::hessian(func = nll_fun, x = theta, y = x) 18 | # nll/g/h with TMB 19 | nll_obj <- gamma_ADFun(x) 20 | ll2 <- nll_obj$fn(theta) 21 | gg2 <- nll_obj$gr(theta)[1,] 22 | hh2 <- nll_obj$he(theta) 23 | # check they are identical 24 | expect_equal(ll1, ll2) 25 | expect_equal(gg1, gg2) 26 | expect_equal(hh1, hh2) 27 | } 28 | }) 29 | -------------------------------------------------------------------------------- /tests/testthat/test-hadamard.R: -------------------------------------------------------------------------------- 1 | 2 | context("hadamard") 3 | 4 | test_that("hadamard calculates elementwise matrix multiplication correctly", { 5 | nreps <- 20 6 | for(ii in 1:nreps) { 7 | n <- sample(10:100, 1) 8 | p <- sample(10:100,1) 9 | A <- matrix(rnorm(n*p), n, p) 10 | B <- matrix(rnorm(n*p), n, p) 11 | C_r <- A * B 12 | C_cpp <- hadamard(A, B) 13 | expect_equal(C_r, C_cpp) 14 | } 15 | }) 16 | -------------------------------------------------------------------------------- /tests/testthat/test-norm_ADFun.R: -------------------------------------------------------------------------------- 1 | 2 | context("norm_ADFun") 3 | 4 | 5 | test_that("norm_ADFun calculates correct negloglik, gradient, and hessian", { 6 | nll_fun <- function(theta, y) { 7 | -sum(dnorm(x = x, mean = theta[1], sd = theta[2], log = TRUE)) 8 | } 9 | nreps <- 20 10 | for(ii in 1:nreps) { 11 | # simulate data/parameters 12 | n <- sample(10:100, 1) 13 | x <- rnorm(n) 14 | theta <- c(mu = rnorm(1), sigma = rexp(1)) 15 | # nll/g/h/ with R + numDeriv 16 | ll1 <- nll_fun(theta, x) 17 | gg1 <- numDeriv::grad(func = nll_fun, x = theta, y = x) 18 | hh1 <- numDeriv::hessian(func = nll_fun, x = theta, y = x) 19 | # nll/g/h with TMB 20 | nll_obj <- norm_ADFun(x) 21 | ll2 <- nll_obj$fn(theta) 22 | gg2 <- nll_obj$gr(theta)[1,] 23 | hh2 <- nll_obj$he(theta) 24 | # check they are identical 25 | expect_equal(ll1, ll2) 26 | expect_equal(gg1, gg2) 27 | expect_equal(hh1, hh2) 28 | } 29 | }) 30 | -------------------------------------------------------------------------------- /vignettes/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | *.R 3 | -------------------------------------------------------------------------------- /vignettes/GammaNLL.hpp: -------------------------------------------------------------------------------- 1 | /// @file GammaNLL.hpp 2 | 3 | #ifndef GammaNLL_hpp 4 | #define GammaNLL_hpp 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | 9 | // negative log-likelihood of the gamma distribution 10 | template 11 | Type GammaNLL(objective_function* obj) { 12 | DATA_VECTOR(x); // data vector 13 | PARAMETER(alpha); // shape parameter 14 | PARAMETER(beta); // scale parameter 15 | return -sum(dgamma(x, alpha, beta, true)); 16 | } 17 | 18 | #undef TMB_OBJECTIVE_PTR 19 | #define TMB_OBJECTIVE_PTR this 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /vignettes/MyTMBPackage_TMBExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by TMB: do not edit by hand 2 | 3 | #define TMB_LIB_INIT R_init_MyTMBPackage_TMBExports 4 | #include 5 | #include "ModelA.hpp" 6 | #include "ModelB.hpp" 7 | #include "ModelC.hpp" 8 | 9 | template 10 | Type objective_function::operator() () { 11 | DATA_STRING(model); 12 | if(model == "ModelA") { 13 | return ModelA(this); 14 | } else if(model == "ModelB") { 15 | return ModelB(this); 16 | } else if(model == "ModelC") { 17 | return ModelC(this); 18 | } else { 19 | Rf_error("Unknown model."); 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /vignettes/NormalNLL.cpp: -------------------------------------------------------------------------------- 1 | /// @file NormalNLL.cpp 2 | 3 | #include 4 | 5 | /// Negative log-likelihood of the normal distribution. 6 | template 7 | Type objective_function::operator() () { 8 | DATA_VECTOR(x); // data vector 9 | PARAMETER(mu); // mean parameter 10 | PARAMETER(sigma); // standard deviation parameter 11 | return -sum(dnorm(x,mu,sigma,true)); // negative log likelihood 12 | } 13 | -------------------------------------------------------------------------------- /vignettes/NormalNLL.hpp: -------------------------------------------------------------------------------- 1 | /// @file NormalNLL.hpp 2 | 3 | #ifndef NormalNLL_hpp 4 | #define NormalNLL_hpp 5 | 6 | #undef TMB_OBJECTIVE_PTR 7 | #define TMB_OBJECTIVE_PTR obj 8 | 9 | /// Negative log-likelihood of the normal distribution. 10 | template 11 | Type NormalNLL(objective_function* obj) { 12 | DATA_VECTOR(x); // data vector 13 | PARAMETER(mu); // mean parameter 14 | PARAMETER(sigma); // standard deviation parameter 15 | return -sum(dnorm(x,mu,sigma,true)); // negative log likelihood 16 | } 17 | 18 | #undef TMB_OBJECTIVE_PTR 19 | #define TMB_OBJECTIVE_PTR this 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /vignettes/TMBtools.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Getting Started with **TMBtools**" 3 | author: "Martin Lysy" 4 | date: "`r Sys.Date()`" 5 | params: 6 | local_pkg: FALSE 7 | reinstall: FALSE 8 | output: 9 | rmarkdown::html_vignette: 10 | toc: yes 11 | vignette: > 12 | %\VignetteIndexEntry{Getting Started with TMBtools} 13 | %\VignetteEngine{knitr::rmarkdown} 14 | %\VignetteEncoding{UTF-8} 15 | --- 16 | 17 | \newcommand{\bm}[1]{\boldsymbol{#1}} 18 | \newcommand{\xx}{\bm{x}} 19 | \newcommand{\zz}{\bm{z}} 20 | \newcommand{\tth}{\bm{\theta}} 21 | \newcommand{\N}{\mathcal N} 22 | \newcommand{\iid}{\stackrel{\mathrm{iid}}{\sim}} 23 | 24 | 41 | 42 | ```{r setup, include = FALSE} 43 | # knitr options 44 | knitr::opts_chunk$set( 45 | collapse = TRUE, 46 | comment = "#>" 47 | ) 48 | # package links 49 | pkg_link <- function(pkg, link) { 50 | if(link == "github") { 51 | link <- paste0("https://github.com/mlysy/", pkg) 52 | } else if(link == "cran") { 53 | link <- paste0("https://CRAN.R-project.org/package=", pkg) 54 | } 55 | paste0("[**", pkg, "**](", link, ")") 56 | } 57 | 58 | # tmb system files 59 | tmb_sysfile <- function(...) { 60 | system.file("templates", ..., package = "TMBtools") 61 | } 62 | 63 | 64 | if(params$local_pkg) { 65 | tmbdir <- "/Users/mlysy/Documents/R/test/TMB" 66 | } else { 67 | # install package to temporary folder 68 | tmbdir <- tempfile(pattern = "TMBtools_vignette") 69 | } 70 | pkgname <- "MyTMBPackage" 71 | ``` 72 | 73 | ## Overview 74 | 75 | `r pkg_link("TMB", "cran")` is an **R** package providing a convenient interface to the `r pkg_link("CppAD", "https://coin-or.github.io/CppAD/doc/cppad.htm")` **C++** library for [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). More specifically for the purpose of statistical inference, **TMB** provides an automatic and extremely efficient implementation of [Laplace's method](https://en.wikipedia.org/wiki/Laplace%27s_method) to approximately integrate out the latent variables of a model $p(\xx \mid \tth) = \int p(\xx, \zz \mid \tth) \, \mathrm{d} \zz$ via numerical optimization. **TMB** is extensively [documented](https://kaskr.github.io/adcomp/_book/Introduction.html), and numerous [examples](https://kaskr.github.io/adcomp/_book/Examples.html#example-overview) indicate that it can be used to effectively handle tens to thousands of latent variables in a model. 76 | 77 | **TMB** was designed for users to compile and save standalone statistical models. Distributing one or more **TMB** models as part of an **R** package requires a nontrivial compilation process (`Makevars[.win]`), and some amount of boilerplate code. Thus, the purpose of **TMBtools** is to provide helper functions for the development of **R** packages which contain **TMB** source code. The main package functions are: 78 | 79 | - `tmb_create_package()`, which creates an **R** package infrastructure with the proper **TMB** compile instructions. 80 | 81 | - `use_tmb()`, which adds **TMB** functionality to an existing package. 82 | 83 | - `export_models()`, which updates the package's **TMB** compile instructions when new models are added. 84 | 85 | **Note to Developers:** While **TMBtools** depends on a number of packages to facilitate its work, none of these dependencies are passed on to your package, except **TMB** itself. 86 | 87 | ## Quickstart 88 | 89 | Let's start with the canonical example of the model univariate normal model 90 | $$ 91 | x_1, \ldots, x_n \iid \N(\mu, \sigma). 92 | $$ 93 | The **TMB** C++ file for creating the negative loglikelihood for this model is given below: 94 | ```{r, echo = FALSE, results = "asis"} 95 | cat("```cpp", 96 | readLines("NormalNLL.cpp"), 97 | "```", sep = "\n") 98 | ``` 99 | For including this model in a package using **TMBtools**, the code must be modified slightly: 100 | 101 | ```{r, echo = FALSE, results = "asis"} 102 | cat("```cpp", 103 | readLines(tmb_sysfile("NormalNLL.hpp")), 104 | "```", sep = "\n") 105 | ``` 106 | Most of the changes can be easily spotted, but a few deserving special attention are outlined below: 107 | 108 | - In the package, **TMB** models should be in `.hpp` header files as opposed to `.cpp` main files. 109 | 110 | - At the time of this writing, **never `#include ` in the header files**. The reason is that this file is not [include-guarded](https://en.wikipedia.org/wiki/Include_guard), so if the package has multiple model files the C++ compiler will complain. 111 | 112 | - The name of the model specified inside the `.hpp` file must *exactly match* the name of the `.hpp` file itself (in this case, `NormalNLL`). Otherwise, **TMBtools** won't be able to find it. 113 | 114 | ### Creating an R Package 115 | 116 | In order to create an **R**/**TMB** package containing `NormalNLL.hpp`, we can use `tmb_create_package()` as follows: 117 | 118 | ```{r, eval = FALSE} 119 | # in a directory where you want to create the package, which also contains NormalNLL.hpp 120 | TMBtools::tmb_create_package("MyTMBPackage", 121 | tmb_files = "NormalNLL.hpp") 122 | ``` 123 | ```{r, echo = FALSE} 124 | if(!params$local_pkg || params$reinstall) { 125 | TMBtools::tmb_create_package(file.path(tmbdir, pkgname), 126 | tmb_files = "NormalNLL.hpp", open = FALSE) 127 | } 128 | ``` 129 | This creates a package that is ready to use right out-of-the-box. In other words, we now run 130 | ```{r, eval = FALSE} 131 | devtools::install() # must have devtools installed 132 | ``` 133 | ```{r, include = FALSE} 134 | if(params$local_pkg) { 135 | if(params$reinstall) { 136 | devtools::install(file.path(tmbdir, pkgname)) 137 | } 138 | ## suppressMessages(require(MyTMBPackage)) 139 | } else { 140 | pkgbuild::compile_dll(file.path(tmbdir, pkgname)) 141 | devtools::load_all(file.path(tmbdir, pkgname)) 142 | dyn.load(TMB::dynlib(file.path(tmbdir, pkgname, 143 | "src", paste0(pkgname, "_TMBExports")))) 144 | } 145 | ``` 146 | Once the package is installed, we can use its **TMB** models very similarly as we would for standalone models: 147 | ```{r} 148 | # might have to quit & restart R first, then 149 | # require(MyTMBPackage) 150 | 151 | # create the negative loglikelihood object 152 | x <- rnorm(100) # data 153 | normal_nll <- TMB::MakeADFun(data = list(model = "NormalNLL", x = x), 154 | parameters = c(mu = 0, sigma = 1), 155 | DLL = "MyTMBPackage_TMBExports", silent = TRUE) 156 | 157 | # call the function and its gradients 158 | theta <- list(mu = -1, sigma = 2) # parameter values 159 | normal_nll$fn(theta) # negative loglikelihood at theta 160 | -sum(dnorm(x, mean = theta$mu, sd = theta$sigma, log = TRUE)) # R check 161 | normal_nll$gr(theta) # nll gradient at theta 162 | normal_nll$he(theta) # hessian at theta 163 | ``` 164 | The notable differences from standalone usage are are: 165 | 166 | - The `data` argument to `TMB::MakeADFun()` has an additional argument `model` to specify which package model to use. Thus we could have different model files `ModelA.hpp`, `ModelB.hpp`, etc., each with their own set of arguments, and we just pick the one to use when the `TMB::MakeADFun()` object is instantiated. 167 | 168 | - The `DLL` argument to `TMB::MakeADFun()` must be of the form `{PackageName}_TMBExports`, where `{PackageName}` is the name of the package in which the **TMB** models are to be looked for. 169 | 170 | ## Adding **TMB** Files 171 | 172 | Suppose we wish to add a **TMB** model to the package contained in `NewModel.hpp`. The simplest way to add this model to **MyTMBPackage** is as follows: 173 | 174 | 1. Copy `NewModel.hpp` to `MyTMBPackage/src/TMB`. 175 | 176 | 2. Run the command 177 | 178 | ```{r, eval = FALSE} 179 | TMBtools::export_models() 180 | ``` 181 | 182 | from within **MyTMBPackage** or any of its subfolders. 183 | 184 | 3. Recompile the package. 185 | 186 | ### Additional `#include` Directives 187 | 188 | `TMBtools::export_models()` will assume that all `.hpp` files in `src/TMB` correspond to **TMB** models, and `#include`s each of them into a single standalone-type meta-model file `src/TMB/MyTMBPackage_TMBExports.cpp`, which contains `if/else` switches to select between the individual **TMB** models. For example, the meta-model file might look like this: 189 | ```{r, echo = FALSE, results = "asis"} 190 | cat("```cpp", 191 | readLines("MyTMBPackage_TMBExports.cpp"), 192 | "```", sep = "\n") 193 | ``` 194 | 195 | This approach works fine when each **TMB** model is contained in a single `.hpp` file. For a larger project it might be desirable to use the **C++** `#include` mechanism to organize things. 196 | 197 | So let's suppose that `src/TMB/ModelA.hpp` wants to `#include` file `helper.hpp`. One way to do this is to store it in the package-level subdirectory `inst/include/MyTMBPackage`. For this to work, we need to tell the **TMB** compiler where to look, which is achieved through the package's `src/Makevars[.win]` file: 198 | 199 | 200 | ```{r, echo = FALSE, results = "asis"} 201 | cat("```bash", 202 | readLines(tmb_sysfile("Makevars")), 203 | "```", sep = "\n") 204 | ``` 205 | The relevant line is that which begins with `## TMB_FLAGS`. Indeed, this variable can be used to pass additional flags to the **TMB** compiler. A common application is to use 206 | 207 | ```bash 208 | TMB_FLAGS = -I"../../inst/include" 209 | ``` 210 | 211 | To tell the **TMB** compiler to also look for `.hpp` (or other) files in any subdirectory of `inst/include`. To summarize, `#include`ing `helper.hpp` in `src/TMB/ModelA.hpp` is accomplished in the following steps: 212 | 213 | 1. Copy `helper.hpp` to `inst/include/MyTMBPackage`. 214 | 2. Add the `TMB_FLAGS` above to both `src/Makevars` and `src/Makevars.win`. 215 | 3. Add the following line to `src/TMB/ModelA.hpp`: 216 | 217 | ```cpp 218 | #include "MyTMBPackage/helper.hpp" 219 | ``` 220 | 221 | We may note that a slightly simpler alternative is to add `helper.hpp` to e.g., `src/TMB/include`, such that the `#include` directive in `ModelA.hpp` becomes 222 | ```cpp 223 | #include "include/helper.hpp" 224 | ``` 225 | The advantage of this approach is that the `src/Makevars[.win]` files don't need to be modified. However, the advantage of the first approach is that storing files in `inst/include` makes them available to developers wanting to `#include` them in other **R**/**TMB** packages, for which the mechanism is to add 226 | ``` 227 | LinkingTo: MyTMBPackage 228 | ``` 229 | In the other package's `DESCRIPTION` file. See [here](https://r-pkgs.org/src.html) or [here](https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Package-Dependencies) for more information. 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | --------------------------------------------------------------------------------