diff --git a/.Rbuildignore b/.Rbuildignore index 91114bf..019a4e8 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,2 +1,6 @@ ^.*\.Rproj$ ^\.Rproj\.user$ +^LICENSE\.md$ +^\.github$ +^attic$ +^README\.Rmd$ diff --git a/.github/.gitignore b/.github/.gitignore new file mode 100644 index 0000000..2d19fc7 --- /dev/null +++ b/.github/.gitignore @@ -0,0 +1 @@ +*.html diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml new file mode 100644 index 0000000..562fe0f --- /dev/null +++ b/.github/workflows/R-CMD-check.yaml @@ -0,0 +1,51 @@ +# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples +# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help +on: + push: + branches: [main, master] + pull_request: + +name: R-CMD-check.yaml + +permissions: read-all + +jobs: + R-CMD-check: + runs-on: ${{ matrix.config.os }} + + name: ${{ matrix.config.os }} (${{ matrix.config.r }}) + + strategy: + fail-fast: false + matrix: + config: + - {os: macos-latest, r: 'release'} + - {os: windows-latest, r: 'release'} + - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} + - {os: ubuntu-latest, r: 'release'} + - {os: ubuntu-latest, r: 'oldrel-1'} + + env: + GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} + R_KEEP_PKG_SOURCE: yes + + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-pandoc@v2 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: ${{ matrix.config.r }} + http-user-agent: ${{ matrix.config.http-user-agent }} + use-public-rspm: true + + - uses: r-lib/actions/setup-r-dependencies@v2 + with: + extra-packages: any::rcmdcheck + needs: check + + - uses: r-lib/actions/check-r-package@v2 + with: + upload-snapshots: true + build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' diff --git a/DESCRIPTION b/DESCRIPTION index fd5b0ee..19787c9 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,26 +1,25 @@ -Package: expard Type: Package -Title: Drug EXPosures and ADRs +Package: expard +Title: Drug 'EXPosures' and 'ADRs' Version: 1.0.0 -Author: Louis Dijkstra -Maintainer: Louis Dijkstra -Description: An R package for fitting complex drug exposure - and adverse drug reaction (ADR) relationships -Depends: - R (>= 3.4.3), - ggplot2, - crayon, - dplyr, - Matrix, - parallel -License: GPL-3 -Encoding: UTF-8 -LazyData: true -RoxygenNote: 7.2.3 -Roxygen: list(markdown = TRUE) +Authors@R: + person("Louis", "Dijkstra", , "louisdijkstra@gmail.com", role = c("aut", "cre")) +Description: An R package for fitting complex drug exposure and adverse + drug reaction ('ADR') relationships. It can additionally be used to + simulate electronic healthcare record ('EHR') data of patients + observed across multiple timepoints. +License: GPL (>= 3) URL: https://github.com/bips-hb/expard BugReports: https://github.com/bips-hb/expard/issues -Suggests: - knitr, - rmarkdown -VignetteBuilder: knitr +Imports: + crayon, + dplyr, + ggplot2, + Matrix, + parallel, + rlang, + stats, + utils +Encoding: UTF-8 +Roxygen: list(markdown = TRUE) +RoxygenNote: 7.3.2 diff --git a/LICENSE b/LICENSE deleted file mode 100755 index e72bfdd..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..175443c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,595 @@ +GNU General Public License +========================== + +_Version 3, 29 June 2007_ +_Copyright © 2007 Free Software Foundation, Inc. <>_ + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +## Preamble + +The GNU General Public License is a free, copyleft license for software and other +kinds of works. + +The licenses for most software and other practical works are designed to take away +your freedom to share and change the works. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change all versions of a +program--to make sure it remains free software for all its users. We, the Free +Software Foundation, use the GNU General Public License for most of our software; it +applies also to any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General +Public Licenses are designed to make sure that you have the freedom to distribute +copies of free software (and charge for them if you wish), that you receive source +code or can get it if you want it, that you can change the software or use pieces of +it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or +asking you to surrender the rights. Therefore, you have certain responsibilities if +you distribute copies of the software, or if you modify it: responsibilities to +respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, +you must pass on to the recipients the same freedoms that you received. You must make +sure that they, too, receive or can get the source code. And you must show them these +terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: **(1)** assert +copyright on the software, and **(2)** offer you this License giving you legal permission +to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is +no warranty for this free software. For both users' and authors' sake, the GPL +requires that modified versions be marked as changed, so that their problems will not +be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of +the software inside them, although the manufacturer can do so. This is fundamentally +incompatible with the aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we have designed +this version of the GPL to prohibit the practice for those products. If such problems +arise substantially in other domains, we stand ready to extend this provision to +those domains in future versions of the GPL, as needed to protect the freedom of +users. + +Finally, every program is threatened constantly by software patents. States should +not allow patents to restrict development and use of software on general-purpose +computers, but in those that do, we wish to avoid the special danger that patents +applied to a free program could make it effectively proprietary. To prevent this, the +GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in +a fashion requiring copyright permission, other than the making of an exact copy. The +resulting work is called a “modified version” of the earlier work or a +work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on +the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for infringement under +applicable copyright law, except executing it on a computer or modifying a private +copy. Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the +extent that it includes a convenient and prominently visible feature that **(1)** +displays an appropriate copyright notice, and **(2)** tells the user that there is no +warranty for the work (except to the extent that warranties are provided), that +licensees may convey the work under this License, and how to view a copy of this +License. If the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code + +The “source code” for a work means the preferred form of the work for +making modifications to it. “Object code” means any non-source form of a +work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of interfaces +specified for a particular programming language, one that is widely used among +developers working in that language. + +The “System Libraries” of an executable work include anything, other than +the work as a whole, that **(a)** is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and **(b)** serves only to +enable use of the work with that Major Component, or to implement a Standard +Interface for which an implementation is available to the public in source code form. +A “Major Component”, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system (if any) on which +the executable work runs, or a compiler used to produce the work, or an object code +interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the +source code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. However, +it does not include the work's System Libraries, or general-purpose tools or +generally available free programs which are used unmodified in performing those +activities but which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for the work, and +the source code for shared libraries and dynamically linked subprograms that the work +is specifically designed to require, such as by intimate data communication or +control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +### 2. Basic Permissions + +All rights granted under this License are granted for the term of copyright on the +Program, and are irrevocable provided the stated conditions are met. This License +explicitly affirms your unlimited permission to run the unmodified Program. The +output from running a covered work is covered by this License only if the output, +given its content, constitutes a covered work. This License acknowledges your rights +of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey covered +works to others for the sole purpose of having them make modifications exclusively +for you, or provide you with facilities for running those works, provided that you +comply with the terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for you must do so +exclusively on your behalf, under your direction and control, on terms that prohibit +them from making any copies of your copyrighted material outside their relationship +with you. + +Conveying under any other circumstances is permitted solely under the conditions +stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law + +No covered work shall be deemed part of an effective technological measure under any +applicable law fulfilling obligations under article 11 of the WIPO copyright treaty +adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention +of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of +technological measures to the extent such circumvention is effected by exercising +rights under this License with respect to the covered work, and you disclaim any +intention to limit operation or modification of the work as a means of enforcing, +against the work's users, your or third parties' legal rights to forbid circumvention +of technological measures. + +### 4. Conveying Verbatim Copies + +You may convey verbatim copies of the Program's source code as you receive it, in any +medium, provided that you conspicuously and appropriately publish on each copy an +appropriate copyright notice; keep intact all notices stating that this License and +any non-permissive terms added in accord with section 7 apply to the code; keep +intact all notices of the absence of any warranty; and give all recipients a copy of +this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer +support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions + +You may convey a work based on the Program, or the modifications to produce it from +the Program, in the form of source code under the terms of section 4, provided that +you also meet all of these conditions: + +* **a)** The work must carry prominent notices stating that you modified it, and giving a +relevant date. +* **b)** The work must carry prominent notices stating that it is released under this +License and any conditions added under section 7. This requirement modifies the +requirement in section 4 to “keep intact all notices”. +* **c)** You must license the entire work, as a whole, under this License to anyone who +comes into possession of a copy. This License will therefore apply, along with any +applicable section 7 additional terms, to the whole of the work, and all its parts, +regardless of how they are packaged. This License gives no permission to license the +work in any other way, but it does not invalidate such permission if you have +separately received it. +* **d)** If the work has interactive user interfaces, each must display Appropriate Legal +Notices; however, if the Program has interactive interfaces that do not display +Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are +not by their nature extensions of the covered work, and which are not combined with +it such as to form a larger program, in or on a volume of a storage or distribution +medium, is called an “aggregate” if the compilation and its resulting +copyright are not used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work in an aggregate +does not cause this License to apply to the other parts of the aggregate. + +### 6. Conveying Non-Source Forms + +You may convey a covered work in object code form under the terms of sections 4 and +5, provided that you also convey the machine-readable Corresponding Source under the +terms of this License, in one of these ways: + +* **a)** Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by the Corresponding Source fixed on a +durable physical medium customarily used for software interchange. +* **b)** Convey the object code in, or embodied in, a physical product (including a +physical distribution medium), accompanied by a written offer, valid for at least +three years and valid for as long as you offer spare parts or customer support for +that product model, to give anyone who possesses the object code either **(1)** a copy of +the Corresponding Source for all the software in the product that is covered by this +License, on a durable physical medium customarily used for software interchange, for +a price no more than your reasonable cost of physically performing this conveying of +source, or **(2)** access to copy the Corresponding Source from a network server at no +charge. +* **c)** Convey individual copies of the object code with a copy of the written offer to +provide the Corresponding Source. This alternative is allowed only occasionally and +noncommercially, and only if you received the object code with such an offer, in +accord with subsection 6b. +* **d)** Convey the object code by offering access from a designated place (gratis or for +a charge), and offer equivalent access to the Corresponding Source in the same way +through the same place at no further charge. You need not require recipients to copy +the Corresponding Source along with the object code. If the place to copy the object +code is a network server, the Corresponding Source may be on a different server +(operated by you or a third party) that supports equivalent copying facilities, +provided you maintain clear directions next to the object code saying where to find +the Corresponding Source. Regardless of what server hosts the Corresponding Source, +you remain obligated to ensure that it is available for as long as needed to satisfy +these requirements. +* **e)** Convey the object code using peer-to-peer transmission, provided you inform +other peers where the object code and Corresponding Source of the work are being +offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the +Corresponding Source as a System Library, need not be included in conveying the +object code work. + +A “User Product” is either **(1)** a “consumer product”, which +means any tangible personal property which is normally used for personal, family, or +household purposes, or **(2)** anything designed or sold for incorporation into a +dwelling. In determining whether a product is a consumer product, doubtful cases +shall be resolved in favor of coverage. For a particular product received by a +particular user, “normally used” refers to a typical or common use of +that class of product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected to use, the +product. A product is a consumer product regardless of whether the product has +substantial commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified version of +its Corresponding Source. The information must suffice to ensure that the continued +functioning of the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for +use in, a User Product, and the conveying occurs as part of a transaction in which +the right of possession and use of the User Product is transferred to the recipient +in perpetuity or for a fixed term (regardless of how the transaction is +characterized), the Corresponding Source conveyed under this section must be +accompanied by the Installation Information. But this requirement does not apply if +neither you nor any third party retains the ability to install modified object code +on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to +continue to provide support service, warranty, or updates for a work that has been +modified or installed by the recipient, or for the User Product in which it has been +modified or installed. Access to a network may be denied when the modification itself +materially and adversely affects the operation of the network or violates the rules +and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with +this section must be in a format that is publicly documented (and with an +implementation available to the public in source code form), and must require no +special password or key for unpacking, reading or copying. + +### 7. Additional Terms + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. Additional +permissions that are applicable to the entire Program shall be treated as though they +were included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part may be +used separately under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when you +modify the work.) You may place additional permissions on material, added by you to a +covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a +covered work, you may (if authorized by the copyright holders of that material) +supplement the terms of this License with terms: + +* **a)** Disclaiming warranty or limiting liability differently from the terms of +sections 15 and 16 of this License; or +* **b)** Requiring preservation of specified reasonable legal notices or author +attributions in that material or in the Appropriate Legal Notices displayed by works +containing it; or +* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that +modified versions of such material be marked in reasonable ways as different from the +original version; or +* **d)** Limiting the use for publicity purposes of names of licensors or authors of the +material; or +* **e)** Declining to grant rights under trademark law for use of some trade names, +trademarks, or service marks; or +* **f)** Requiring indemnification of licensors and authors of that material by anyone +who conveys the material (or modified versions of it) with contractual assumptions of +liability to the recipient, for any liability that these contractual assumptions +directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further +restrictions” within the meaning of section 10. If the Program as you received +it, or any part of it, contains a notice stating that it is governed by this License +along with a term that is a further restriction, you may remove that term. If a +license document contains a further restriction but permits relicensing or conveying +under this License, you may add to a covered work material governed by the terms of +that license document, provided that the further restriction does not survive such +relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in +the relevant source files, a statement of the additional terms that apply to those +files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a +separately written license, or stated as exceptions; the above requirements apply +either way. + +### 8. Termination + +You may not propagate or modify a covered work except as expressly provided under +this License. Any attempt otherwise to propagate or modify it is void, and will +automatically terminate your rights under this License (including any patent licenses +granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated **(a)** provisionally, unless and until the +copyright holder explicitly and finally terminates your license, and **(b)** permanently, +if the copyright holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently +if the copyright holder notifies you of the violation by some reasonable means, this +is the first time you have received notice of violation of this License (for any +work) from that copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of +parties who have received copies or rights from you under this License. If your +rights have been terminated and not permanently reinstated, you do not qualify to +receive new licenses for the same material under section 10. + +### 9. Acceptance Not Required for Having Copies + +You are not required to accept this License in order to receive or run a copy of the +Program. Ancillary propagation of a covered work occurring solely as a consequence of +using peer-to-peer transmission to receive a copy likewise does not require +acceptance. However, nothing other than this License grants you permission to +propagate or modify any covered work. These actions infringe copyright if you do not +accept this License. Therefore, by modifying or propagating a covered work, you +indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients + +Each time you convey a covered work, the recipient automatically receives a license +from the original licensors, to run, modify and propagate that work, subject to this +License. You are not responsible for enforcing compliance by third parties with this +License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an organization, or +merging organizations. If propagation of a covered work results from an entity +transaction, each party to that transaction who receives a copy of the work also +receives whatever licenses to the work the party's predecessor in interest had or +could give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if the predecessor +has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or +affirmed under this License. For example, you may not impose a license fee, royalty, +or other charge for exercise of rights granted under this License, and you may not +initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging +that any patent claim is infringed by making, using, selling, offering for sale, or +importing the Program or any portion of it. + +### 11. Patents + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The work thus +licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter acquired, that +would be infringed by some manner, permitted by this License, of making, using, or +selling its contributor version, but do not include claims that would be infringed +only as a consequence of further modification of the contributor version. For +purposes of this definition, “control” includes the right to grant patent +sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license +under the contributor's essential patent claims, to make, use, sell, offer for sale, +import and otherwise run, modify and propagate the contents of its contributor +version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent (such as an +express permission to practice a patent or covenant not to sue for patent +infringement). To “grant” such a patent license to a party means to make +such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of charge +and under the terms of this License, through a publicly available network server or +other readily accessible means, then you must either **(1)** cause the Corresponding +Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the +patent license for this particular work, or **(3)** arrange, in a manner consistent with +the requirements of this License, to extend the patent license to downstream +recipients. “Knowingly relying” means you have actual knowledge that, but +for the patent license, your conveying the covered work in a country, or your +recipient's use of the covered work in a country, would infringe one or more +identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you +convey, or propagate by procuring conveyance of, a covered work, and grant a patent +license to some of the parties receiving the covered work authorizing them to use, +propagate, modify or convey a specific copy of the covered work, then the patent +license you grant is automatically extended to all recipients of the covered work and +works based on it. + +A patent license is “discriminatory” if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on the +non-exercise of one or more of the rights that are specifically granted under this +License. You may not convey a covered work if you are a party to an arrangement with +a third party that is in the business of distributing software, under which you make +payment to the third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties who would receive +the covered work from you, a discriminatory patent license **(a)** in connection with +copies of the covered work conveyed by you (or copies made from those copies), or **(b)** +primarily for and in connection with specific products or compilations that contain +the covered work, unless you entered into that arrangement, or that patent license +was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available to you +under applicable patent law. + +### 12. No Surrender of Others' Freedom + +If conditions are imposed on you (whether by court order, agreement or otherwise) +that contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot convey a covered work so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not convey it at all. For example, if you +agree to terms that obligate you to collect a royalty for further conveying from +those to whom you convey the Program, the only way you could satisfy both those terms +and this License would be to refrain entirely from conveying the Program. + +### 13. Use with the GNU Affero General Public License + +Notwithstanding any other provision of this License, you have permission to link or +combine any covered work with a work licensed under version 3 of the GNU Affero +General Public License into a single combined work, and to convey the resulting work. +The terms of this License will continue to apply to the part which is the covered +work, but the special requirements of the GNU Affero General Public License, section +13, concerning interaction through a network will apply to the combination as such. + +### 14. Revised Versions of this License + +The Free Software Foundation may publish revised and/or new versions of the GNU +General Public License from time to time. Such new versions will be similar in spirit +to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that +a certain numbered version of the GNU General Public License “or any later +version” applies to it, you have the option of following the terms and +conditions either of that numbered version or of any later version published by the +Free Software Foundation. If the Program does not specify a version number of the GNU +General Public License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU +General Public License can be used, that proxy's public statement of acceptance of a +version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no +additional obligations are imposed on any author or copyright holder as a result of +your choosing to follow a later version. + +### 15. Disclaimer of Warranty + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE +QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +### 16. Limitation of Liability + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY +COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS +PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE +OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE +WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16 + +If the disclaimer of warranty and limitation of liability provided above cannot be +given local legal effect according to their terms, reviewing courts shall apply local +law that most closely approximates an absolute waiver of all civil liability in +connection with the Program, unless a warranty or assumption of liability accompanies +a copy of the Program in return for a fee. + +_END OF TERMS AND CONDITIONS_ + +## How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to +the public, the best way to achieve this is to make it free software which everyone +can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them +to the start of each source file to most effectively state the exclusion of warranty; +and each file should have at least the “copyright” line and a pointer to +where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this +when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type 'show c' for details. + +The hypothetical commands `show w` and `show c` should show the appropriate parts of +the General Public License. Of course, your program's commands might be different; +for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to +sign a “copyright disclaimer” for the program, if necessary. For more +information on this, and how to apply and follow the GNU GPL, see +<>. + +The GNU General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may consider it +more useful to permit linking proprietary applications with the library. If this is +what you want to do, use the GNU Lesser General Public License instead of this +License. But first, please read +<>. diff --git a/NAMESPACE b/NAMESPACE index 7c89b8a..26141ae 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -35,3 +35,16 @@ export(risk_model_long_term) export(risk_model_no_association) export(risk_model_past) export(risk_model_withdrawal) +importFrom(Matrix,Matrix) +importFrom(crayon,blue) +importFrom(crayon,green) +importFrom(crayon,red) +importFrom(rlang,.data) +importFrom(stats,BIC) +importFrom(stats,dnorm) +importFrom(stats,optim) +importFrom(stats,rbinom) +importFrom(stats,reorder) +importFrom(utils,setTxtProgressBar) +importFrom(utils,tail) +importFrom(utils,txtProgressBar) diff --git a/R/apply-function-to-observed-timepoints.R b/R/apply-function-to-observed-timepoints.R index 2178ea9..ad94181 100644 --- a/R/apply-function-to-observed-timepoints.R +++ b/R/apply-function-to-observed-timepoints.R @@ -1,35 +1,35 @@ #' Apply Function to Subset Drug History -#' -#' Observations might not be present for certain patients, since they entered -#' the data set later time = 1 or before the end. This function applies, for -#' example, a risk model only to the observed time points. -#' -#' @param drug_history The drug history. Unobserved time points are denoted by +#' +#' Observations might not be present for certain patients, since they entered +#' the data set later time = 1 or before the end. This function applies, for +#' example, a risk model only to the observed time points. +#' +#' @param drug_history The drug history. Unobserved time points are denoted by #' \code{NA} -#' @param fn A function (Default \code{\link{risk_model_current_use}}). -#' +#' @param fn A function (Default \code{\link{risk_model_current_use}}). +#' #' @return Vector of the same length as \code{drug_history}. None observed time points #' are denoted by \code{NA} -#' @export -apply_function_to_observed_timepoints <- function(drug_history, - fn = expard::risk_model_current_use()) { - +#' @export +apply_function_to_observed_timepoints <- function( + drug_history, + fn = expard::risk_model_current_use()) { simulation_time <- length(drug_history) - + # determine the indices that are not NA indices_not_NA <- which(!is.na(drug_history)) - + # get only the observed drug history given these indices observed_drug_history <- drug_history[indices_not_NA] - + # determine the values for only this part of the drug history values_fn <- fn(observed_drug_history) - + # initialize the risk vector with the same length as the original drug history values <- rep(NA, simulation_time) - + # fill in the observed risks values[indices_not_NA] <- values_fn - + return(values) -} \ No newline at end of file +} diff --git a/R/create2x2table.R b/R/create2x2table.R index ac04ec5..69a2fd0 100644 --- a/R/create2x2table.R +++ b/R/create2x2table.R @@ -1,146 +1,142 @@ #' Creating a \eqn{2 \times 2} Table -#' -#' Creates a \eqn{2 \times 2} contingency table for a +#' +#' Creates a \eqn{2 \times 2} contingency table for a #' drug and ADR. \cr\cr -#' A table is structured in the following form: +#' A table is structured in the following form: #' \tabular{lcc}{ #' \tab ADR \tab not ADR\cr #' drug \tab \code{a} \tab \code{c}\cr #' not drug \tab \code{b} \tab \code{d} #' } -#' -#' # Ways to construct the table -#' The counts can be constructed in three different ways. See for -#' two of them Zorych et al. (2013). -#' -#' ## By individual time-points (\code{time-point}) -#' Each time-point is counted separately. The counts are the +#' +#' # Ways to construct the table +#' The counts can be constructed in three different ways. See for +#' two of them Zorych et al. (2013). +#' +#' ## By individual time-points (\code{time-point}) +#' Each time-point is counted separately. The counts are the #' \emph{number of time points} that -#' \itemize{ +#' \itemize{ #' \item{\code{a} - the drug was prescribed and the ADR occurred} #' \item{\code{b} - the drug was not prescribed but the ADR occurred} #' \item{\code{c} - the drug was prescribed but the ADR did not occur} #' \item{\code{d} - the drug was not prescribed and the ADR did not occur} #' } -#' Note that in this case the total count \code{n = a + b + c + d} is -#' the same as the total number of time points observed, i.e., the total -#' number of patients times the number of time points observed: -#' \code{n_patients * simulation_time}. -#' +#' Note that in this case the total count \code{n = a + b + c + d} is +#' the same as the total number of time points observed, i.e., the total +#' number of patients times the number of time points observed: +#' \code{n_patients * simulation_time}. +#' #' ## By individual patients (\code{patient}) -#' In this case, individual patients are counted. The counts are the \emph{number -#' of patients} that +#' In this case, individual patients are counted. The counts are the \emph{number +#' of patients} that #' \itemize{ #' \item{\code{a} - were prescribed the drug and did experience the ADR } #' \item{\code{b} - were never prescribed the drug and did experience the ADR} #' \item{\code{c} - were prescribed the drug and never experienced the ADR} #' \item{\code{d} - were never prescribed the drug and never experienced the ADR} #' } -#' In this case, the total count \code{n = a + b + c +d} is the same as +#' In this case, the total count \code{n = a + b + c +d} is the same as #' the number of patients, \code{n_patients}. -#' +#' #' ## By individual patients (\code{drug-era}) -#' In this case we look at \emph{drug-eras}, i.e., periods in which the -#' patients was prescribed or not prescribed the drug for a longer time. -#' For example, if the patient was prescribed the drug from time point 3 to -#' 6, then that period is called a drug-era. -#' The counts are the \emph{number of drug- and non-drug eras} in which -#' \itemize{ +#' In this case we look at \emph{drug-eras}, i.e., periods in which the +#' patients was prescribed or not prescribed the drug for a longer time. +#' For example, if the patient was prescribed the drug from time point 3 to +#' 6, then that period is called a drug-era. +#' The counts are the \emph{number of drug- and non-drug eras} in which +#' \itemize{ #' \item{\code{a} - the drug was prescribed and the ADR occurred} #' \item{\code{b} - the drug was not prescribed but the ADR occurred} #' \item{\code{c} - the drug was prescribed but the ADR did not occur} #' \item{\code{d} - the drug was not prescribed and the ADR did not occur} #' } -#' In this case, the total count \code{n} is the total number of drug- and +#' In this case, the total count \code{n} is the total number of drug- and #' non-drug eras. -#' -#' @param drug_ADR_pair A drug-ADR pair; see \code{\link{generate_cohort}} -#' @param method Method used to construct the table; either -#' \code{time-point}, \code{drug-era} and \code{patient}. -#' See the description for more information (Default: +#' +#' @param drug_ADR_pair A drug-ADR pair; see \code{\link{generate_cohort}} +#' @param method Method used to construct the table; either +#' \code{time-point}, \code{drug-era} and \code{patient}. +#' See the description for more information (Default: #' \code{time-point}) #' -#' @return A \code{cont_table} object; a list with +#' @return A \code{cont_table} object; a list with #' \item{\code{a},\code{b},\code{c},\code{d}}{The counts in the table} #' \item{\code{method}}{Method that was used to construct the table} -#' \item{\code{n}}{Total count (\code{n = a + b + c + d}). The interpretation -#' depends on the \code{method} used} +#' \item{\code{n}}{Total count (\code{n = a + b + c + d}). The interpretation +#' depends on the \code{method} used} #' -#' @references -#' Zorych, I., Madigan, D., Ryan, P., & Bate, A. (2013). Disproportionality methods for -#' pharmacovigilance in longitudinal observational databases. -#' Statistical Methods in Medical Research, 22(1), 39–56. -#' https://doi.org/10.1177/0962280211403602 +#' @references +#' Zorych, I., Madigan, D., Ryan, P., & Bate, A. (2013). Disproportionality methods for +#' pharmacovigilance in longitudinal observational databases. +#' Statistical Methods in Medical Research, 22(1), 39–56. +#' https://doi.org/10.1177/0962280211403602 #' @seealso \code{\link{generate_cohort}} -#' @examples +#' @examples #' set.seed(1) -#' cohort <- generate_cohort(n_patients = 200) -#' -#' # create the 2x2 contingency table per time-point, -#' # drug-era and patient: +#' cohort <- generate_cohort(n_patients = 200) +#' +#' # create the 2x2 contingency table per time-point, +#' # drug-era and patient: #' create2x2table(cohort, method = "time-point") #' create2x2table(cohort, method = "drug-era") #' create2x2table(cohort, method = "patient") #' @export -create2x2table <- function(drug_ADR_pair, method = c("time-point", - "drug-era", - "patient")) { - - if (!(method[1] %in% c("time-point", "drug-era", "patient"))) { - stop(sprintf("method should be either '%s', '%s' or '%s'", - "time-point", "drug-era", "patient")) - } - +create2x2table <- function( + drug_ADR_pair, + method = c( + "time-point", + "drug-era", + "patient" + ) +) { + method <- match.arg(method) + # initialize tables - table <- list(a = 0, b = 0, c = 0, d = 0, method = method[1]) - class(table) <- "cont_table" - - if (method[1] == "time-point") { - - drug <- drug_ADR_pair$drug_history == 1 + out_table <- list(a = 0, b = 0, c = 0, d = 0, method = method[1]) + class(out_table) <- "cont_table" + + if (method == "time-point") { + drug <- drug_ADR_pair$drug_history == 1 ADR <- drug_ADR_pair$adr_history == 1 - - table$a <- sum(drug & ADR, na.rm = TRUE) - table$b <- sum(!drug & ADR, na.rm = TRUE) - table$c <- sum(drug & !ADR, na.rm = TRUE) - table$d <- sum(!drug & !ADR, na.rm = TRUE) + + out_table$a <- sum(drug & ADR, na.rm = TRUE) + out_table$b <- sum(!drug & ADR, na.rm = TRUE) + out_table$c <- sum(drug & !ADR, na.rm = TRUE) + out_table$d <- sum(!drug & !ADR, na.rm = TRUE) } - - if (method[1] == "patient") { + + if (method == "patient") { # go over all patients drug <- rowSums(as.matrix(drug_ADR_pair$drug_history), na.rm = TRUE) > 0 ADR <- rowSums(as.matrix(drug_ADR_pair$adr_history), na.rm = TRUE) > 0 - - table$a <- sum(drug & ADR, na.rm = TRUE) - table$b <- sum(!drug & ADR, na.rm = TRUE) - table$c <- sum(drug & !ADR, na.rm = TRUE) - table$d <- sum(!drug & !ADR, na.rm = TRUE) + + out_table$a <- sum(drug & ADR, na.rm = TRUE) + out_table$b <- sum(!drug & ADR, na.rm = TRUE) + out_table$c <- sum(drug & !ADR, na.rm = TRUE) + out_table$d <- sum(!drug & !ADR, na.rm = TRUE) } - - if (method[1] == "drug-era") { - - - - sapply(1:cohort$n_patients, function(k) { - + + if (method == "drug-era") { + sapply(seq_len(drug_ADR_pair$n_patients), function(k) { # remove any none observed time points. They are represented by NAs indices_observed_time_points_drug <- which(!is.na(drug_ADR_pair$drug_history[k, ])) indices_observed_time_points_adr <- which(!is.na(drug_ADR_pair$adr_history[k, ])) indices_observed_time_points <- union(indices_observed_time_points_drug, indices_observed_time_points_adr) - + drug_history_patient <- drug_ADR_pair$drug_history[k, indices_observed_time_points] adr_history_patient <- drug_ADR_pair$adr_history[k, indices_observed_time_points] - + simulation_time_patient <- length(drug_history_patient) - + # first initialize some variables to keep track # in which era we (drug or non-drug) and whether # the ADR occured during this era in_drug_era <- - drug_history_patient[1] == 1 # are we currently in a drug era? + drug_history_patient[1] == 1 # are we currently in a drug era? ADR_happened <- - drug_history_patient[1] == 1 # did the ADR occur during this era? - + drug_history_patient[1] == 1 # did the ADR occur during this era? + sapply(2:(simulation_time_patient - 1), function(t) { if (in_drug_era) { # in drug-era @@ -154,9 +150,9 @@ create2x2table <- function(drug_ADR_pair, method = c("time-point", # switch from a drug-era to a non-drug era in_drug_era <- FALSE if (ADR_happened) { - table$a <<- table$a + 1 + out_table$a <<- out_table$a + 1 } else { - table$c <<- table$c + 1 + out_table$c <<- out_table$c + 1 } } } else { @@ -171,39 +167,42 @@ create2x2table <- function(drug_ADR_pair, method = c("time-point", # switch from a non-drug-era to a drug era in_drug_era <- TRUE if (ADR_happened) { - table$b <<- table$b + 1 + out_table$b <<- out_table$b + 1 } else { - table$d <<- table$d + 1 + out_table$d <<- out_table$d + 1 } } - } ADR_happened <- adr_history_patient[t] == 1 }) }) } - - - table$n <- table$a + table$b + table$c + table$d - - return(table) + + + out_table$n <- out_table$a + out_table$b + out_table$c + out_table$d + + return(out_table) } #' Print function for 2x2 tables +#' @param x A \code{cont_table} object. +#' @param ... Unused. #' @export -print.cont_table <- function(table) { +print.cont_table <- function(x, ...) { cat(sprintf("2 x 2 Contingency Table\n")) - cat(sprintf("\tusing method '%s'\n\n", table$method)) + cat(sprintf("\tusing method '%s'\n\n", x$method)) cat(" |\tADR\t| not ADR\t| total\n") cat("------------------------------------------------\n") - cat(sprintf(" drug |\t%d\t|\t%d\t| %d\n", table$a, table$c, table$a + table$c)) - cat(sprintf("not drug |\t%d\t|\t%d\t| %d\n", table$b, table$d, table$b + table$d)) + cat(sprintf(" drug |\t%d\t|\t%d\t| %d\n", x$a, x$c, x$a + x$c)) + cat(sprintf("not drug |\t%d\t|\t%d\t| %d\n", x$b, x$d, x$b + x$d)) cat("------------------------------------------------\n") - cat(sprintf(" total |\t%d\t|\t%d\t| %d\n", table$a + table$b, - table$c + table$d, - table$a + table$b + table$c + table$d)) - - if ((table$a + table$c) == (table$a + table$b + table$c + table$d)) { - cat(crayon::magenta(sprintf("\nwarning: since the number of patients that were prescribed \nthe drug and the total number of patients is the same,\nit might be that the cohort was created like this on purpose"))) + cat(sprintf( + " total |\t%d\t|\t%d\t| %d\n", x$a + x$b, + x$c + x$d, + x$a + x$b + x$c + x$d + )) + + if ((x$a + x$c) == (x$a + x$b + x$c + x$d)) { + cat(crayon::magenta(sprintf("\nwarning: since the number of patients that were prescribed \nthe drug and the total number of patients is the same,\nit might be that the cohort was created like this on purpose"))) } -} \ No newline at end of file +} diff --git a/R/create2x2tables.R b/R/create2x2tables.R index d61bb07..226f7e7 100644 --- a/R/create2x2tables.R +++ b/R/create2x2tables.R @@ -1,118 +1,121 @@ #' \eqn{2 \times 2} Tables -#' -#' Creates the \eqn{2 \times 2} contingency tables for *all* +#' +#' Creates the \eqn{2 \times 2} contingency tables for *all* #' drug-ADR pairs in a specific cohort. The function is basically #' a wrapper for \code{\link{create2x2table}} -#' +#' #' \cr\cr -#' A table is structured in the following form: +#' A table is structured in the following form: #' \tabular{lcc}{ #' \tab ADR \tab not ADR\cr #' drug \tab \code{a} \tab \code{c}\cr #' not drug \tab \code{b} \tab \code{d} #' } -#' -#' # Ways to construct the table -#' The counts can be constructed in three different ways. See for -#' two of them Zorych et al. (2013). -#' -#' ## By individual time-points (\code{time-point}) -#' Each time-point is counted separately. The counts are the +#' +#' # Ways to construct the table +#' The counts can be constructed in three different ways. See for +#' two of them Zorych et al. (2013). +#' +#' ## By individual time-points (\code{time-point}) +#' Each time-point is counted separately. The counts are the #' \emph{number of time points} that -#' \itemize{ +#' \itemize{ #' \item{\code{a} - the drug was prescribed and the ADR occurred} #' \item{\code{b} - the drug was not prescribed but the ADR occurred} #' \item{\code{c} - the drug was prescribed but the ADR did not occur} #' \item{\code{d} - the drug was not prescribed and the ADR did not occur} #' } -#' Note that in this case the total count \code{n = a + b + c + d} is -#' the same as the total number of time points observed, i.e., the total -#' number of patients times the number of time points observed: -#' \code{n_patients * simulation_time}. -#' +#' Note that in this case the total count \code{n = a + b + c + d} is +#' the same as the total number of time points observed, i.e., the total +#' number of patients times the number of time points observed: +#' \code{n_patients * simulation_time}. +#' #' ## By individual patients (\code{patient}) -#' In this case, individual patients are counted. The counts are the \emph{number -#' of patients} that +#' In this case, individual patients are counted. The counts are the \emph{number +#' of patients} that #' \itemize{ #' \item{\code{a} - were prescribed the drug and did experience the ADR } #' \item{\code{b} - were never prescribed the drug and did experience the ADR} #' \item{\code{c} - were prescribed the drug and never experienced the ADR} #' \item{\code{d} - were never prescribed the drug and never experienced the ADR} #' } -#' In this case, the total count \code{n = a + b + c +d} is the same as +#' In this case, the total count \code{n = a + b + c +d} is the same as #' the number of patients, \code{n_patients}. -#' +#' #' ## By individual patients (\code{drug-era}) -#' In this case we look at \emph{drug-eras}, i.e., periods in which the -#' patients was prescribed or not prescribed the drug for a longer time. -#' For example, if the patient was prescribed the drug from time point 3 to -#' 6, then that period is called a drug-era. -#' The counts are the \emph{number of drug- and non-drug eras} in which -#' \itemize{ +#' In this case we look at \emph{drug-eras}, i.e., periods in which the +#' patients was prescribed or not prescribed the drug for a longer time. +#' For example, if the patient was prescribed the drug from time point 3 to +#' 6, then that period is called a drug-era. +#' The counts are the \emph{number of drug- and non-drug eras} in which +#' \itemize{ #' \item{\code{a} - the drug was prescribed and the ADR occurred} #' \item{\code{b} - the drug was not prescribed but the ADR occurred} #' \item{\code{c} - the drug was prescribed but the ADR did not occur} #' \item{\code{d} - the drug was not prescribed and the ADR did not occur} #' } -#' In this case, the total count \code{n} is the total number of drug- and +#' In this case, the total count \code{n} is the total number of drug- and #' non-drug eras. -#' -#' @param cohort A cohort; see \code{\link{generate_cohort}} -#' @param method Method used to construct the table; either -#' \code{time-point}, \code{drug-era} and \code{patient}. -#' See the description for more information (Default: +#' +#' @param cohort A cohort; see \code{\link{generate_cohort}} +#' @param method Method used to construct the table; either +#' \code{time-point}, \code{drug-era} and \code{patient}. +#' See the description for more information (Default: #' \code{time-point}) +#' @param verbose If \code{TRUE} (default), a progress bar is shown #' #' @return A list of \code{cont_table} objects #' -#' @references -#' Zorych, I., Madigan, D., Ryan, P., & Bate, A. (2013). Disproportionality methods for -#' pharmacovigilance in longitudinal observational databases. -#' Statistical Methods in Medical Research, 22(1), 39–56. -#' https://doi.org/10.1177/0962280211403602 +#' @references +#' Zorych, I., Madigan, D., Ryan, P., & Bate, A. (2013). Disproportionality methods for +#' pharmacovigilance in longitudinal observational databases. +#' Statistical Methods in Medical Research, 22(1), 39–56. +#' https://doi.org/10.1177/0962280211403602 #' @seealso \code{\link{create2x2table}} -#' @examples +#' @examples #' set.seed(1) -#' cohort <- generate_cohort(n_patients = 200) -#' -#' # create the 2x2 contingency table per time-point, -#' # drug-era and patient: +#' cohort <- generate_cohort(n_patients = 200) +#' +#' # create the 2x2 contingency table per time-point, +#' # drug-era and patient: #' create2x2table(cohort, method = "time-point") #' create2x2table(cohort, method = "drug-era") #' create2x2table(cohort, method = "patient") #' @export create2x2tables <- function(cohort, - method = c("time-point", - "drug-era", - "patient"), + method = c( + "time-point", + "drug-era", + "patient" + ), verbose = TRUE) { - - - if (!(method[1] %in% c("time-point", "drug-era", "patient"))) { - stop(sprintf("method should be either '%s', '%s' or '%s'", - "time-point", "drug-era", "patient")) + if (!(method[1] %in% c("time-point", "drug-era", "patient"))) { + stop(sprintf( + "method should be either '%s', '%s' or '%s'", + "time-point", "drug-era", "patient" + )) } - - if (verbose) { + + if (verbose) { cat("Generating 2x2 tables...\n") - pb <- txtProgressBar(min = 0, max = cohort$n_drug_ADR_pairs, style = 3) + pb <- txtProgressBar(min = 0, max = cohort$n_drug_ADR_pairs, style = 3) } - + # initialize tables - tables <- lapply(1:cohort$n_drug_ADR_pairs, function(i) { + tables <- lapply(1:cohort$n_drug_ADR_pairs, function(i) { table <- create2x2table(cohort[[i]], method) - + if (verbose) { setTxtProgressBar(pb, i) } - + return(table) }) - + if (verbose) { - close(pb) + close(pb) cat("DONE generating tables...\n") } - + return(tables) } diff --git a/R/determine-first-prescription.R b/R/determine-first-prescription.R index bf70e60..89b2e69 100644 --- a/R/determine-first-prescription.R +++ b/R/determine-first-prescription.R @@ -1,42 +1,45 @@ #' First Prescription -#' +#' #' \code{determine_first_perscription} returns a time point -#' for the first prescription of the drug of interest +#' for the first prescription of the drug of interest #' given the time frame of the patient (\code{simulation_time}) #' and the chance for it be prescribed is \code{min_chance_drug}. #' The patient, in this case, is always prescribed the drug at least -#' once. The time point follows a \eqn{\Gamma} distribution. -#' -#' \emph{Note:} we assume here that the probability of -#' the drug being prescribed does not depend on any previous prescriptions. -#' +#' once. The time point follows a \eqn{\Gamma} distribution. +#' +#' \emph{Note:} we assume here that the probability of +#' the drug being prescribed does not depend on any previous prescriptions. +#' #' @param n_patients Number of patients (Default: 1) #' @param simulation_time The total number of time points for this patient -#' @param min_chance_drug The probability of the drug being prescribed +#' @param min_chance_drug The probability of the drug being prescribed #' at any given time point -#' +#' #' @return A time point between \code{1} and \code{simulation_time} -#' @examples +#' @examples #' set.seed(1) #' determine_first_prescription(n_patients = 4, simulation_time = 10, min_chance_drug = 0.1) -#' # -> [1] 2 3 5 9 +#' # -> [1] 2 3 5 9 #' @export -determine_first_prescription <- function(n_patients, simulation_time, min_chance_drug) { - +determine_first_prescription <- function(n_patients, simulation_time, min_chance_drug) { # check correctness input -------- - if (n_patients < 1) { stop("n_patients should be >= 1") } - if (simulation_time < 1) { stop("simulation_time should be >= 1") } - if (min_chance_drug <= 0 || min_chance_drug > 1) { - stop("min_chance_drug should be in the interval (0,1]") + if (n_patients < 1) { + stop("n_patients should be >= 1") } - + if (simulation_time < 1) { + stop("simulation_time should be >= 1") + } + if (min_chance_drug <= 0 || min_chance_drug > 1) { + stop("min_chance_drug should be in the interval (0,1]") + } + # determining the probabilities that the drug is prescribed at each # time point (1, 2, ..., simulation_time). Follows a Gamma distribution probs <- sapply(1:simulation_time, function(t) (1 - min_chance_drug)^(t - 1)) probs <- probs * min_chance_drug / sum(probs) # normalization - + # sample a random time point given the probabilities return( sample(x = 1:simulation_time, n_patients, replace = TRUE, prob = probs) ) -} \ No newline at end of file +} diff --git a/R/determine-frequency-unique-values.R b/R/determine-frequency-unique-values.R index e842913..534a7e8 100644 --- a/R/determine-frequency-unique-values.R +++ b/R/determine-frequency-unique-values.R @@ -1,35 +1,35 @@ #' Compute Frequency Table -#' -#' Determine how often different values from time_steps_ago -#' appear in the data set and how often the ADR occurs for -#' each of them. This is used for speeding up the computation of the +#' +#' Determine how often different values from time_steps_ago +#' appear in the data set and how often the ADR occurs for +#' each of them. This is used for speeding up the computation of the #' loglikeihood -#' +#' #' @param mat Matrix with relevant values (depends on model) #' @param adr_history History of ADRs -#' +#' #' @return Tibble #' @export determine_frequency_unique_values <- function(mat, adr_history) { unique_values <- sort(unique(as.vector(mat))) - + freq_table <- lapply(sort(unique_values), function(unique_value) { # where does this 'unique_value' occur in the data indices <- which(mat == unique_value) - + # count how often an ADR occurred at those time points n_adr <- sum(adr_history[indices]) - + c( unique_value = unique_value, - freq = length(indices), + freq = length(indices), # how often does it occur - n_adr = n_adr, - n_no_adr = length(indices) - n_adr + n_adr = n_adr, + n_no_adr = length(indices) - n_adr ) }) - + # create a tibble and return it return(dplyr::as_tibble(do.call(rbind, freq_table))) -} \ No newline at end of file +} diff --git a/R/expard-package.R b/R/expard-package.R new file mode 100644 index 0000000..dc19cf8 --- /dev/null +++ b/R/expard-package.R @@ -0,0 +1,19 @@ +#' @keywords internal +"_PACKAGE" + +## usethis namespace: start +#' @importFrom crayon blue +#' @importFrom crayon green +#' @importFrom crayon red +#' @importFrom Matrix Matrix +#' @importFrom rlang .data +#' @importFrom stats BIC +#' @importFrom stats dnorm +#' @importFrom stats optim +#' @importFrom stats rbinom +#' @importFrom stats reorder +#' @importFrom utils setTxtProgressBar +#' @importFrom utils tail +#' @importFrom utils txtProgressBar +## usethis namespace: end +NULL diff --git a/R/fit-all-models.R b/R/fit-all-models.R index c4d94ee..96bbf80 100644 --- a/R/fit-all-models.R +++ b/R/fit-all-models.R @@ -1,89 +1,103 @@ #' @export -fit_all_models <- function(pair, - models = c( - 'no-association', - 'current-use', - 'past-use', - 'withdrawal', - 'delayed', - 'decaying', - 'delayed+decaying', - 'long-term' - ), - zero_patients = 0, - zero_timepoints = 0, - method = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", - "Brent"), - maxiter = 1000, - parameters = list(), - mc.cores = 1) { - +#' @rdname fit_model +#' @param parameters Passed to [fit_model()] +#' @param mc.cores Number of cores used for parallelization +fit_all_models <- function( + cohort, + models = c( + "no-association", + "current-use", + "past-use", + "withdrawal", + "delayed", + "decaying", + "delayed+decaying", + "long-term" + ), + zero_patients = 0, + zero_timepoints = 0, + method = c( + "L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", + "Brent" + ), + maxiter = 1000, + parameters = list(), + mc.cores = 1 +) { + run_parallel <- FALSE + if (mc.cores > 1) { run_parallel <- TRUE - cluster <- makeCluster(mc.cores) - clusterEvalQ(cluster, {library(dplyr); library(expard)}) - clusterExport(cluster, c("pair", "models", "method", "maxiter", "parameters"), envir = environment()) - + cluster <- parallel::makeCluster(mc.cores) + parallel::clusterEvalQ(cluster, { + require(dplyr) + require(expard) + }) + parallel::parallelclusterExport( + cluster, c("pair", "models", "method", "maxiter", "parameters"), + envir = environment() + ) + cat(sprintf("Running in parallel with %d cores\n", mc.cores)) } - + fit_model_local_function <- function(model) { cat(sprintf("Fitting model %s...\n", model)) - fit_model(pair, model, zero_patients, zero_timepoints, method, maxiter, parameters) + fit_model(cohort, model, zero_patients, zero_timepoints, method, maxiter, parameters) } - + if (run_parallel) { - - # if past-use is a model, we divide it into many model fits, + # if past-use is a model, we divide it into many model fits, # one for each value of the past parameter. This makes it easier # to parallelize the entire thing - if ('past-use' %in% models) { - models <- models[models != 'past-use'] - simulation_time <- ncol(pair$drug_history) + if ("past-use" %in% models) { + models <- models[models != "past-use"] + simulation_time <- ncol(cohort$drug_history) past <- 1:(simulation_time - 1) models <- c(models, sprintf("past-use(%d)", past)) } - - res_temp <- parLapply(cluster, models, function(model) { + + res_temp <- parallel::parLapply(cluster, models, function(model) { cat(sprintf("Fitting model %s...\n", model)) - expard::fit_model(pair, model, zero_patients, zero_timepoints, method, maxiter, parameters) - })#fit_model_local_function(model)) + fit_model(cohort, model, zero_patients, zero_timepoints, method, maxiter, parameters) + }) # fit_model_local_function(model)) } else { - res_temp <- lapply(models, function(model) { + res_temp <- lapply(models, function(model) { cat(sprintf("Fitting model %s...\n", model)) - expard::fit_model(pair, model, zero_patients, zero_timepoints, method, maxiter, parameters) - })#fit_model_local_function(model)) + fit_model(cohort, model, zero_patients, zero_timepoints, method, maxiter, parameters) + }) # fit_model_local_function(model)) } if (run_parallel) { - stopCluster(cluster) + parallel::stopCluster(cluster) } - + res <- res_temp[[1]] - - for(i in 2:length(res_temp)) { - res <- full_join(res, res_temp[[i]]) + + for (i in 2:length(res_temp)) { + res <- dplyr::full_join(res, res_temp[[i]]) } - - #res$BIC <- res$n_param * log(res$n_patients * res$simulation_time) + 2*res$loglikelihood - - # determine the posterior probability for each model - # use the parameter setting of the model with the best BIC + + # res$BIC <- res$n_param * log(res$n_patients * res$simulation_time) + 2*res$loglikelihood + + # determine the posterior probability for each model + # use the parameter setting of the model with the best BIC min_BIC <- min(res$bestBIC) - - r <- res %>% - group_by(model) %>% - slice_min(n = 1, BIC) %>% - mutate(delta_BIC = BIC - min_BIC) - - denominator <- sum(exp(-r$delta_BIC/2)) - r <- r %>% mutate( - posterior = exp(-delta_BIC / 2) / denominator - ) - - r <- r %>% dplyr::select(model, posterior) - - res <- full_join(r, res) - - return(res %>% dplyr::arrange(-posterior)) -} \ No newline at end of file + + r <- res |> + dplyr::group_by(.data$model) |> + dplyr::slice_min(n = 1, .data$BIC) |> + dplyr::mutate(delta_BIC = .data$BIC - min_BIC) + + denominator <- sum(exp(-r$delta_BIC / 2)) + + r <- r |> + dplyr::mutate( + posterior = exp(-.data$delta_BIC / 2) / denominator + ) |> + dplyr::select(c("model", "posterior")) + + r |> + dplyr::full_join(res) |> + dplyr::arrange(dplyr::desc(posterior)) +} diff --git a/R/fit-model.R b/R/fit-model.R index 2439d33..341502b 100644 --- a/R/fit-model.R +++ b/R/fit-model.R @@ -1,37 +1,40 @@ #' Fit a Model to Cohort Data -#' +#' #' \code{fit_model} fits a specified risk model \code{risk_model} -#' to cohort data. -#' -#' @section Patient models: -#' \code{fit_model} can currently only deal with the +#' to cohort data. +#' +#' @section Patient models: +#' \code{fit_model} can currently only deal with the #' \code{\link{patient_model_uninformative}}. More complex -#' patient models, such as \code{\link{patient_model_sex}} +#' patient models, such as \code{\link{patient_model_sex}} #' require the estimation of more parameters which is currently -#' not supported. +#' not supported. #' @section Cohort data object: -#' Minimal requirement is that the cohort is a list with +#' Minimal requirement is that the cohort is a list with #' two matrix with the items #' \itemize{ -#' \item{\code{drug_history} A binary matrix of size +#' \item{\code{drug_history} A binary matrix of size #' \code{n_patients x simulation_time} describing #' the drug prescriptions.} -#' \item{\code{adr_history} A binary matrix of size +#' \item{\code{adr_history} A binary matrix of size #' \code{n_patients x simulation_time} describing #' ADR histories} #' } #' See \code{\link{check_cohort}} and \code{\link{generate_cohort}} -#' for more details on the \code{cohort} object. -#' -#' @param cohort A cohort dataset. See details below. +#' for more details on the \code{cohort} object. +#' +#' @param cohort A cohort dataset. See details below. #' @param model Label for a risk model. Can be either ... #' @param start Starting point for the base \code{\link{optim}}-solver #' (Default: \code{c(-1,1)}) #' @param method Methods used by the base \code{\link{optim}}-solver #' @param maxiter Maximum number iterations for the \code{\link{optim}}-solver #' @param control List used by the base \code{\link{optim}}-solver -#' -#' @return A model fit. A list with the items +#' @param zero_patients,zero_timepoints Integer values (TODO) +#' @param parameters list (TODO) +#' +#' +#' @return A model fit. A list with the items #' \item{\code{n_patients}}{Total number of patients in the dataset} #' \item{\code{simulation_time}}{Total number of time points} #' \item{\code{loglikelihood}}{The maximal log-likelihood value} @@ -41,214 +44,221 @@ #' of no ADR occurring} #' \item{\code{prob_ADR_with_drug}}{Estimated probability #' of ADR occurring} -#' \item{\code{convergence}}{Convergence value of \code{\link{optim}}. +#' \item{\code{convergence}}{Convergence value of \code{\link{optim}}. #' \code{0} means that the algorithm converged} -#' +#' #' @seealso \code{\link{check_cohort}},\code{\link{generate_cohort}} -#' @examples -#' cohort <- expard::generate_cohort(n_patients = 1000, -#' simulation_time = 100, -#' risk_model = expard::risk_model_immediate(), -#' verbose = TRUE, -#' min_chance_drug = probability_model_constant(.3), -#' max_chance_drug = probability_model_constant(.7), -#' min_chance_adr = probability_model_constant(.3), -#' max_chance_adr = probability_model_constant(.6)) +#' @examples +#' cohort <- generate_cohort( +#' n_patients = 1000, +#' simulation_time = 100, +#' risk_model = expard::risk_model_withdrawal(rate = 3), +#' verbose = TRUE, +#' min_chance_drug = probability_model_constant(.3), +#' max_chance_drug = probability_model_constant(.7), +#' min_chance_adr = probability_model_constant(.3), +#' max_chance_adr = probability_model_constant(.6) +#' ) #' # fit the no effect model -#' fit_model(cohort, risk_model = expard::risk_model_no_effect()) -#' +#' fit_model(cohort, risk_model = expard::risk_model_no_effect()) +#' #' # fit the true immediate effect model -#' fit_model(cohort, risk_model = expard::risk_model_immediate()) -#' # note that the estimators are close to the truth (.3 and .6) +#' fit_model(cohort, risk_model = expard::risk_model_withdrawal(rate = 3)) +#' # note that the estimators are close to the truth (.3 and .6) #' @export -fit_model <- function(pair, - model = c( - 'no-association', - 'current-use', - 'past-use', - 'withdrawal', - 'delayed', - 'decaying', - 'delayed+decaying', - 'long-term' - ), - zero_patients = 0, - zero_timepoints = 0, - method = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", - "Brent"), - maxiter = 1000, - parameters = list(), - mc.cores = 1) { - - +fit_model <- function( + cohort, + model = c( + "no-association", + "current-use", + "past-use", + "withdrawal", + "delayed", + "decaying", + "delayed+decaying", + "long-term" + ), + zero_patients = 0, + zero_timepoints = 0, + method = c( + "L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", + "Brent" + ), + maxiter = 1000, + parameters = list() +) { + + model <- match.arg(model) + # initialize the fit -------------------------------- fit <- data.frame( - n_patients = nrow(pair$drug_history) + zero_patients, - simulation_time = ncol(pair$drug_history), - model = model[1], - n_param = NA, - loglikelihood = NA, + n_patients = nrow(cohort$drug_history) + zero_patients, + simulation_time = ncol(cohort$drug_history), + model = model, + n_param = NA, + loglikelihood = NA, converged = NA ) - - #class(fit) <- c(class(fit), "expardmodel") - + + # class(fit) <- c(class(fit), "expardmodel") + # No association model ------------------------------------------------------- - if (model[1] == "no-association") { - + if (model == "no-association") { # determine the 2x2 table - table <- expard::create2x2table(pair, method = "time-point") - - # add all the time points of patients that were never exposed + table <- create2x2table(cohort, method = "time-point") + + # add all the time points of patients that were never exposed table$d <- table$d + zero_timepoints - + pi <- (table$a + table$b) / table$n - + fit$p <- pi fit$n_param <- 1 - fit$loglikelihood <- -1*((table$a + table$b) * log(pi) + (table$c + table$d) * log(1 - pi)) + fit$loglikelihood <- -1 * ((table$a + table$b) * log(pi) + (table$c + table$d) * log(1 - pi)) fit$converged <- TRUE fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - - if (model[1] == "current-use") { - # create 2x2 tables - table <- expard::create2x2table(pair, method = "time-point") - - # add all the time points of patients that were never exposed + + + if (model == "current-use") { + # create 2x2 tables + table <- create2x2table(cohort, method = "time-point") + + # add all the time points of patients that were never exposed table$d <- table$d + zero_timepoints - - pi1 <- table$a / (table$a + table$c) + + pi1 <- table$a / (table$a + table$c) pi0 <- table$b / (table$b + table$d) - + fit$n_param <- 2 - fit$loglikelihood <- -1*(table$a)*log(pi1) - (table$c)*log(1 - pi1) - table$b*log(pi0) - (table$d)*log(1 - pi0) + fit$loglikelihood <- -1 * (table$a) * log(pi1) - (table$c) * + log(1 - pi1) - table$b * log(pi0) - (table$d) * log(1 - pi0) fit$converged <- TRUE - + fit$p1 <- pi1 fit$p0 <- pi0 - + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - - - if (model[1] == "past-use") { - - simulation_time <- ncol(pair$drug_history) - n_patients = nrow(pair$drug_history) - + + + if (model == "past-use") { + simulation_time <- ncol(cohort$drug_history) + n_patients <- nrow(cohort$drug_history) + # determine how many time points have not been observed - not_observed_drug <- is.na(pair$drug_history) - not_observed_adr <- is.na(pair$adr_history) + not_observed_drug <- is.na(cohort$drug_history) + not_observed_adr <- is.na(cohort$adr_history) not_observed <- not_observed_drug | not_observed_adr - + # total number of observed timepoints - n_observed_timepoints <- n_patients*simulation_time - sum(not_observed) + zero_timepoints - - past <- 1:(simulation_time - 1) - + n_observed_timepoints <- n_patients * simulation_time - sum(not_observed) + zero_timepoints + + past <- seq_len(simulation_time - 1) + fit <- data.frame( expand.grid( n_patients = n_patients + zero_patients, simulation_time = simulation_time, - model = model[1], + model = model, n_param = 3, loglikelihood = NA, - converged = NA, + converged = NA, past = past ) ) - + cat(sprintf("Parameter 'past': \n")) - pb <- txtProgressBar(min = 1, max = max(past), style = 3) - - estimates <- lapply(past, function(d) { - # select the risk model + pb <- txtProgressBar(min = 1, max = max(past), style = 3) + + estimates <- lapply(past, function(d) { + # select the risk model risk_model <- expard::risk_model_past(d) - + # 'convert' the drug prescriptions. They reflect which period is considered # to have an increased risk risks <- matrix(0, nrow = n_patients, ncol = simulation_time) - - # go over all patients - for (i in 1:n_patients) { - # go over all timepoints - risks[i, ] <- apply_function_to_observed_timepoints(pair$drug_history[i, ], - risk_model) + + # go over all patients + for (i in seq_len(n_patients)) { + # go over all timepoints + risks[i, ] <- apply_function_to_observed_timepoints( + cohort$drug_history[i, ], + risk_model + ) # risks[i, ] <- risk_model(pair$drug_history[i, ]) } - - # given the risk, determine the 2x2 table: - # + + # given the risk, determine the 2x2 table: + # # ADR - # | 1 0 | + # | 1 0 | # ------------------------------------ # risk 1 | n11 n10 | n1. - # 0 | n01 n00 | n0. + # 0 | n01 n00 | n0. # ------------------------------------ # | n.1 n.0 | simulation_time*n_patients - + # determine the marginals n1. <- sum(risks, na.rm = TRUE) - n0. <- n_observed_timepoints - n1. - n.1 <- sum(pair$adr_history, na.rm = TRUE) - n.0 <- n_observed_timepoints - n.1 - - # determine the entries - n11 <- sum(risks & pair$adr_history, na.rm = TRUE) + n0. <- n_observed_timepoints - n1. + n.1 <- sum(cohort$adr_history, na.rm = TRUE) + n.0 <- n_observed_timepoints - n.1 + + # determine the entries + n11 <- sum(risks & cohort$adr_history, na.rm = TRUE) n01 <- n.1 - n11 n10 <- n1. - n11 n00 <- n0. - n01 - + pi1 <- n11 / n1. pi0 <- n01 / n0. - + setTxtProgressBar(pb, d) - return(list(p1 = pi1, - p0 = pi0, - value = -1*n11*log(pi1) - n10*log(1 - pi1) - n01*log(pi0) - n00*log(1 - pi0))) + return(list( + p1 = pi1, + p0 = pi0, + value = -1 * n11 * log(pi1) - n10 * log(1 - pi1) - n01 * log(pi0) - n00 * log(1 - pi0) + )) }) - + close(pb) - + fit$loglikelihood <- sapply(estimates, function(est) est$value) - fit$p0 <- sapply(estimates, function(est) est$p0 ) - fit$p1 <- sapply(estimates, function(est) est$p1 ) - fit$converged <- TRUE #sapply(estimates, function(est) est$convergence == 0) - + fit$p0 <- sapply(estimates, function(est) est$p0) + fit$p1 <- sapply(estimates, function(est) est$p1) + fit$converged <- TRUE # sapply(estimates, function(est) est$convergence == 0) + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - + # if it is a single past model with a fixed past parameter - if (substr(model[1], start = 1, stop = 9) == "past-use(") { - - substr(model[1], start = 1, stop = 9) - d <- as.integer(substr(model[1], 10, nchar(model[1])-1)) - + if (substr(model, start = 1, stop = 9) == "past-use(") { + substr(model, start = 1, stop = 9) + d <- as.integer(substr(model[1], 10, nchar(model[1]) - 1)) + simulation_time <- ncol(pair$drug_history) - n_patients = nrow(pair$drug_history) - + n_patients <- nrow(pair$drug_history) + # determine how many time points have not been observed not_observed_drug <- is.na(pair$drug_history) not_observed_adr <- is.na(pair$adr_history) not_observed <- not_observed_drug | not_observed_adr - + # total number of observed timepoints - n_observed_timepoints <- n_patients*simulation_time - sum(not_observed) + zero_timepoints - + n_observed_timepoints <- n_patients * simulation_time - sum(not_observed) + zero_timepoints + past <- d - + fit <- data.frame( expand.grid( n_patients = n_patients + zero_patients, @@ -256,389 +266,413 @@ fit_model <- function(pair, model = model[1], n_param = 3, loglikelihood = NA, - converged = NA, + converged = NA, past = past ) ) - - estimates <- lapply(past, function(d) { - # select the risk model - risk_model <- expard::risk_model_past(d) - + + estimates <- lapply(past, function(d) { + # select the risk model + risk_model <- risk_model_past(d) + # 'convert' the drug prescriptions. They reflect which period is considered # to have an increased risk risks <- matrix(0, nrow = n_patients, ncol = simulation_time) - - # go over all patients - for (i in 1:n_patients) { - # go over all timepoints - risks[i, ] <- apply_function_to_observed_timepoints(pair$drug_history[i, ], - risk_model) + + # go over all patients + for (i in 1:n_patients) { + # go over all timepoints + risks[i, ] <- apply_function_to_observed_timepoints( + pair$drug_history[i, ], + risk_model + ) # risks[i, ] <- risk_model(pair$drug_history[i, ]) } - - # given the risk, determine the 2x2 table: - # + + # given the risk, determine the 2x2 table: + # # ADR - # | 1 0 | + # | 1 0 | # ------------------------------------ # risk 1 | n11 n10 | n1. - # 0 | n01 n00 | n0. + # 0 | n01 n00 | n0. # ------------------------------------ # | n.1 n.0 | simulation_time*n_patients - + # determine the marginals n1. <- sum(risks, na.rm = TRUE) - n0. <- n_observed_timepoints - n1. + n0. <- n_observed_timepoints - n1. n.1 <- sum(pair$adr_history, na.rm = TRUE) - n.0 <- n_observed_timepoints - n.1 - - # determine the entries + n.0 <- n_observed_timepoints - n.1 + + # determine the entries n11 <- sum(risks & pair$adr_history, na.rm = TRUE) n01 <- n.1 - n11 n10 <- n1. - n11 n00 <- n0. - n01 - + pi1 <- n11 / n1. pi0 <- n01 / n0. - - return(list(p1 = pi1, - p0 = pi0, - value = -1*n11*log(pi1) - n10*log(1 - pi1) - n01*log(pi0) - n00*log(1 - pi0))) + + return(list( + p1 = pi1, + p0 = pi0, + value = -1 * n11 * log(pi1) - n10 * log(1 - pi1) - n01 * log(pi0) - n00 * log(1 - pi0) + )) }) - + fit$loglikelihood <- sapply(estimates, function(est) est$value) - fit$p0 <- sapply(estimates, function(est) est$p0 ) - fit$p1 <- sapply(estimates, function(est) est$p1 ) - fit$converged <- TRUE #sapply(estimates, function(est) est$convergence == 0) - + fit$p0 <- sapply(estimates, function(est) est$p0) + fit$p1 <- sapply(estimates, function(est) est$p1) + fit$converged <- TRUE # sapply(estimates, function(est) est$convergence == 0) + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - - - if (model[1] == "withdrawal") { + + + if (model == "withdrawal") { # determine times since last exposure for a drug history of a single patient determine_time_steps_ago <- function(drug_history) { - sapply(1:length(drug_history), function(t) { + sapply(1:length(drug_history), function(t) { # currently exposed or did not take the drug yet - if (drug_history[t] == 1 || sum(drug_history[1:t]) == 0) { - return(0) + if (drug_history[t] == 1 || sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - max(which(drug_history[1:t] == 1)) - return(time_steps_ago) + time_steps_ago <- t - max(which(drug_history[1:t] == 1)) + return(time_steps_ago) } }) } - - #apply_function_to_observed_timepoints(pair$drug_history[10,], + + # apply_function_to_observed_timepoints(pair$drug_history[10,], # determine_time_steps_ago) - + n_patients <- nrow(pair$drug_history) - - time_steps_ago <- do.call(rbind, - lapply(1:n_patients, function(i) { - apply_function_to_observed_timepoints(pair$drug_history[i, ], - determine_time_steps_ago) - #determine_time_steps_ago(pair$drug_history[i, ]) - })) - + + time_steps_ago <- do.call( + rbind, + lapply(1:n_patients, function(i) { + apply_function_to_observed_timepoints( + pair$drug_history[i, ], + determine_time_steps_ago + ) + # determine_time_steps_ago(pair$drug_history[i, ]) + }) + ) + freq_table <- expard::determine_frequency_unique_values(time_steps_ago, pair$adr_history) - + # add zero time points - freq_table[1, 'freq'] <- freq_table[1, 'freq'] + zero_timepoints - freq_table[1, 'n_no_adr'] <- freq_table[1, 'n_no_adr'] + zero_timepoints - - res <- optim(c(0,0,-1), - expard::loglikelihood_withdrawal, + freq_table[1, "freq"] <- freq_table[1, "freq"] + zero_timepoints + freq_table[1, "n_no_adr"] <- freq_table[1, "n_no_adr"] + zero_timepoints + + res <- optim(c(0, 0, -1), + loglikelihood_withdrawal, freq_table = freq_table, method = "Nelder-Mead", - control = list(maxit = maxiter)) - + control = list(maxit = maxiter) + ) + beta0 <- res$par[1] beta <- res$par[2] - fit$p0 = exp(beta0) / (1 + exp(beta0)) - fit$p1 = exp(beta) / (1 + exp(beta)) + fit$p0 <- exp(beta0) / (1 + exp(beta0)) + fit$p1 <- exp(beta) / (1 + exp(beta)) fit$rate <- exp(res$par[3]) - + fit$n_param <- 3 fit$loglikelihood <- res$value fit$converged <- res$convergence == 0 - + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - - if (model[1] == "delayed") { - - determine_time_steps_since_start <- function(drug_history) { + + + if (model == "delayed") { + determine_time_steps_since_start <- function(drug_history) { simulation_time <- length(drug_history) - sapply(1:simulation_time, function(t) { + sapply(1:simulation_time, function(t) { # currently exposed or did not take the drug yet - if (sum(drug_history[1:t]) == 0) { - return(0) + if (sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - min(which(drug_history[1:t] == 1)) - return(time_steps_ago) + time_steps_ago <- t - min(which(drug_history[1:t] == 1)) + return(time_steps_ago) } }) } - + n_patients <- nrow(pair$drug_history) - - time_steps_since_start <- do.call(rbind, - lapply(1:n_patients, function(i) { - apply_function_to_observed_timepoints(pair$drug_history[i, ], - determine_time_steps_since_start) - #determine_time_steps_ago(pair$drug_history[i, ]) - })) - - + + time_steps_since_start <- do.call( + rbind, + lapply(1:n_patients, function(i) { + apply_function_to_observed_timepoints( + pair$drug_history[i, ], + determine_time_steps_since_start + ) + # determine_time_steps_ago(pair$drug_history[i, ]) + }) + ) + + freq_table <- determine_frequency_unique_values(time_steps_since_start, pair$adr_history) - + # add zero time points - freq_table[1, 'freq'] <- freq_table[1, 'freq'] + zero_timepoints - freq_table[1, 'n_no_adr'] <- freq_table[1, 'n_no_adr'] + zero_timepoints - - - res <- optim(c(0,0,1,1), - expard::loglikelihood_delayed, + freq_table[1, "freq"] <- freq_table[1, "freq"] + zero_timepoints + freq_table[1, "n_no_adr"] <- freq_table[1, "n_no_adr"] + zero_timepoints + + + res <- optim(c(0, 0, 1, 1), + loglikelihood_delayed, freq_table = freq_table, method = "Nelder-Mead", - control = list(maxit = maxiter)) - + control = list(maxit = maxiter) + ) + beta0 <- res$par[1] beta <- res$par[2] - fit$p0 = exp(beta0) / (1 + exp(beta0)) - fit$p1 = exp(beta) / (1 + exp(beta)) + fit$p0 <- exp(beta0) / (1 + exp(beta0)) + fit$p1 <- exp(beta) / (1 + exp(beta)) fit$mu <- exp(res$par[3]) fit$sigma <- exp(res$par[4]) - + fit$n_param <- 4 fit$loglikelihood <- res$value fit$converged <- res$convergence == 0 - + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - if (model[1] == "decaying") { - - - determine_time_steps <- function(drug_history) { + + if (model == "decaying") { + determine_time_steps <- function(drug_history) { simulation_time <- length(drug_history) - + # never took the drug - if (sum(drug_history) == 0) { + if (sum(drug_history) == 0) { return(rep(0, simulation_time)) } - - sapply(1:simulation_time, function(t) { + + sapply(1:simulation_time, function(t) { # did not take the drug yet - if (sum(drug_history[1:t]) == 0) { - return(0) + if (sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - min(which(drug_history[1:t] == 1)) - return(time_steps_ago) + time_steps_ago <- t - min(which(drug_history[1:t] == 1)) + return(time_steps_ago) } }) } - + n_patients <- nrow(pair$drug_history) - - time_steps <- do.call(rbind, - lapply(1:n_patients, function(i) { - apply_function_to_observed_timepoints(pair$drug_history[i, ], - determine_time_steps) - #determine_time_steps_ago(pair$drug_history[i, ]) - })) - - + + time_steps <- do.call( + rbind, + lapply(1:n_patients, function(i) { + apply_function_to_observed_timepoints( + pair$drug_history[i, ], + determine_time_steps + ) + # determine_time_steps_ago(pair$drug_history[i, ]) + }) + ) + + freq_table <- determine_frequency_unique_values(time_steps, pair$adr_history) - + # add zero time points - freq_table[1, 'freq'] <- freq_table[1, 'freq'] + zero_timepoints - freq_table[1, 'n_no_adr'] <- freq_table[1, 'n_no_adr'] + zero_timepoints - - res <- optim(c(-1,0,log(1)), - expard::loglikelihood_decaying, + freq_table[1, "freq"] <- freq_table[1, "freq"] + zero_timepoints + freq_table[1, "n_no_adr"] <- freq_table[1, "n_no_adr"] + zero_timepoints + + res <- optim(c(-1, 0, log(1)), + expard::loglikelihood_decaying, freq_table = freq_table, method = "Nelder-Mead", - control = list(maxit = maxiter)) - - + control = list(maxit = maxiter) + ) + + beta0 <- res$par[1] beta <- res$par[2] rate_log <- res$par[3] fit$p0 <- exp(beta0) / (1 + exp(beta0)) fit$p1 <- exp(beta) / (1 + exp(beta)) fit$rate <- exp(rate_log) - + fit$n_param <- 3 fit$loglikelihood <- res$value fit$converged <- res$convergence == 0 - + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - - - if (model[1] == "delayed+decaying") { - - determine_time_steps <- function(drug_history) { + + + + if (model == "delayed+decaying") { + determine_time_steps <- function(drug_history) { simulation_time <- length(drug_history) - sapply(1:simulation_time, function(t) { + sapply(1:simulation_time, function(t) { # currently exposed or did not take the drug yet - if (sum(drug_history[1:t]) == 0) { - return(0) + if (sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - min(which(drug_history[1:t] == 1)) - return(time_steps_ago) + time_steps_ago <- t - min(which(drug_history[1:t] == 1)) + return(time_steps_ago) } }) } - + n_patients <- nrow(pair$drug_history) - - time_steps <- do.call(rbind, - lapply(1:n_patients, function(i) { - apply_function_to_observed_timepoints(pair$drug_history[i, ], - determine_time_steps) - #determine_time_steps_ago(pair$drug_history[i, ]) - })) - + + time_steps <- do.call( + rbind, + lapply(1:n_patients, function(i) { + apply_function_to_observed_timepoints( + pair$drug_history[i, ], + determine_time_steps + ) + # determine_time_steps_ago(pair$drug_history[i, ]) + }) + ) + freq_table <- determine_frequency_unique_values(time_steps, pair$adr_history) - + # add zero time points - freq_table[1, 'freq'] <- freq_table[1, 'freq'] + zero_timepoints - freq_table[1, 'n_no_adr'] <- freq_table[1, 'n_no_adr'] + zero_timepoints - + freq_table[1, "freq"] <- freq_table[1, "freq"] + zero_timepoints + freq_table[1, "n_no_adr"] <- freq_table[1, "n_no_adr"] + zero_timepoints + res <- optim(c(-1, 0, log(1), log(1), log(1)), - expard::loglikelihood_delayed_decaying, + loglikelihood_delayed_decaying, freq_table = freq_table, method = "Nelder-Mead", - control = list(maxit = maxiter)) - - + control = list(maxit = maxiter) + ) + + beta0 <- res$par[1] beta <- res$par[2] mu_log <- res$par[3] sigma_log <- res$par[4] rate_log <- res$par[5] - + fit$p0 <- exp(beta0) / (1 + exp(beta0)) - fit$p1 <- exp(beta) / (1 + exp(beta)) + fit$p1 <- exp(beta) / (1 + exp(beta)) fit$mu <- exp(mu_log) fit$sigma <- exp(sigma_log) fit$rate <- exp(rate_log) - + fit$n_param <- 5 fit$loglikelihood <- res$value fit$converged <- res$convergence == 0 - + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - - - if (model[1] == "long-term") { - + + + + if (model == "long-term") { determine_time_steps <- function(drug_history) { simulation_time <- length(drug_history) - + # moment of first prescription sapply(1:simulation_time, function(t) { - # if case the drug was never prescribed + # if case the drug was never prescribed if (sum(drug_history[1:t]) == 0) { return(0) } else { # moment of first prescription return(t - min(which(drug_history[1:t] == 1))) # use a sigmoid function to determine the effect - #return(1 / (1 + exp(-rate * (time_since_first_prescription - delay)))) + # return(1 / (1 + exp(-rate * (time_since_first_prescription - delay)))) } }) } - + n_patients <- nrow(pair$drug_history) - - time_steps <- do.call(rbind, - lapply(1:n_patients, function(i) { - apply_function_to_observed_timepoints(pair$drug_history[i, ], - determine_time_steps) - #determine_time_steps_ago(pair$drug_history[i, ]) - })) - + + time_steps <- do.call( + rbind, + lapply(1:n_patients, function(i) { + apply_function_to_observed_timepoints( + pair$drug_history[i, ], + determine_time_steps + ) + # determine_time_steps_ago(pair$drug_history[i, ]) + }) + ) + freq_table <- determine_frequency_unique_values(time_steps, pair$adr_history) - + # add zero time points - freq_table[1, 'freq'] <- freq_table[1, 'freq'] + zero_timepoints - freq_table[1, 'n_no_adr'] <- freq_table[1, 'n_no_adr'] + zero_timepoints - - res <- optim(c(0,0,0,0), - expard::loglikelihood_long_term, + freq_table[1, "freq"] <- freq_table[1, "freq"] + zero_timepoints + freq_table[1, "n_no_adr"] <- freq_table[1, "n_no_adr"] + zero_timepoints + + res <- optim(c(0, 0, 0, 0), + expard::loglikelihood_long_term, freq_table = freq_table, method = "Nelder-Mead", - control = list(maxit = maxiter)) - + control = list(maxit = maxiter) + ) + beta0 <- res$par[1] beta <- res$par[2] rate_log <- res$par[3] delay_log <- res$par[4] - + fit$p0 <- exp(beta0) / (1 + exp(beta0)) - fit$p1 <- exp(beta) / (1 + exp(beta)) + fit$p1 <- exp(beta) / (1 + exp(beta)) fit$rate <- exp(rate_log) fit$delay <- exp(delay_log) - + fit$n_param <- 4 fit$loglikelihood <- res$value fit$converged <- res$convergence == 0 - + fit$BIC <- fit$n_param * log(fit$n_patients * fit$simulation_time) + 2 * fit$loglikelihood fit$bestBIC <- min(fit$BIC) - + return(fit) } - - stop("model not known") + } #' Print function for the hccd fit_model +#' @param x A \code{expardfit2} object. +#' @param ... Unused. #' @export -print.expardfit2 <- function(fit) { +print.expardfit2 <- function(x, ...) { cat("expard model fit\n") cat("----------------\n\n") - cat(sprintf("no. of patients : %d\n", fit$n_patients)) - cat(sprintf("no. of time points : %d\n\n", fit$simulation_time)) - - if (fit$converged) { + cat(sprintf("no. of patients : %d\n", x$n_patients)) + cat(sprintf("no. of time points : %d\n\n", x$simulation_time)) + + if (x$converged) { cat(green(sprintf("\u2713 CONVERGED\n\n"))) - } else { - cat(red(sprintf("\u2717 DID NOT CONVERGE\n\n"))) + } else { + cat(red(sprintf("\u2717 DID NOT CONVERGE\n\n"))) } - - cat(sprintf("negative log-likelihood : %g\n", fit$loglikelihood)) - cat(sprintf("no. of parameters : %d\n\n", fit$n_param)) - + + cat(sprintf("negative log-likelihood : %g\n", x$loglikelihood)) + cat(sprintf("no. of parameters : %d\n\n", x$n_param)) + cat("estimates:\n\n") - for (i in 1:fit$n_param) { - cat(sprintf("\t-- %s : %g\n", names(fit$est)[i], fit$est[i])) + for (i in 1:x$n_param) { + cat(sprintf("\t-- %s : %g\n", names(x$est)[i], x$est[i])) } } diff --git a/R/generate-adr-history.R b/R/generate-adr-history.R index 41ecb3a..ddc28e5 100644 --- a/R/generate-adr-history.R +++ b/R/generate-adr-history.R @@ -1,28 +1,27 @@ #' Returns ADR History -#' +#' #' Generates a binary vector of ADR occurrences given a drug history -#' and a risk model. -#' -#' @param drug_history Binary vector denoting the +#' and a risk model. +#' +#' @param drug_history Binary vector denoting the #' drug prescriptions history #' @param risk_model A risk model, e.g., \code{\link{risk_model_current_use}} -#' @param min_chance The probability of the ADR when -#' the drug history has no effect -#' @param max_chance The probability of the ADR when +#' @param min_chance The probability of the ADR when +#' the drug history has no effect +#' @param max_chance The probability of the ADR when #' the drug history has the highest possible effect -#' +#' #' @return Binary vector of the same length as \code{drug_history} #' @export -generate_adr_history <- function(drug_history, - risk_model, - min_chance, - max_chance, - ...) { - +generate_adr_history <- function( + drug_history, + risk_model, + min_chance, + max_chance +) { simulation_time <- length(drug_history) prob <- min_chance + (max_chance - min_chance) * risk_model(drug_history, min_chance, max_chance) - - adr_history <- sapply(prob, function(p) rbinom(1,1,p)) - return(adr_history) -} \ No newline at end of file + + sapply(prob, function(p) rbinom(1, 1, p)) +} diff --git a/R/generate-cohort.R b/R/generate-cohort.R index 01fecb3..1e2d1a1 100644 --- a/R/generate-cohort.R +++ b/R/generate-cohort.R @@ -1,44 +1,44 @@ -#' Generate a Cohort -#' -#' Generates a cohort which is a collection of drug-ADR pair. -#' It is a wrapper function for the \code{\link{generate_patient}} -#' function. -#' -#' @param n_patients Number of patients +#' Generate a Cohort +#' +#' Generates a cohort which is a collection of drug-ADR pair. +#' It is a wrapper function for the \code{\link{generate_patient}} +#' function. +#' +#' @param n_patients Number of patients +#' @param prob_guaranteed_exposed Probability of guaranteed exposure #' @inheritParams generate_patient #' @param verbose Show progress bar (Default: \code{FALSE}) -#' -#' @return A \code{cohort} object; A list of length \code{n_drug_ADR_pairs}. +#' +#' @return A \code{cohort} object; A list of length \code{n_drug_ADR_pairs}. #' Each entry contains two binary matrices; one for the drug histories -#' of all patients and one for the ADR histories of all patients. Each +#' of all patients and one for the ADR histories of all patients. Each #' row is a patient -#' -#' @seealso \code{\link{generate_patient}} +#' +#' @seealso \code{\link{generate_patient}} #' @export -generate_cohort <- function(n_patients = 100, - simulation_time = 100, - n_drug_ADR_pairs = 50, - risk_model = rep("risk_model_current_use()", n_drug_ADR_pairs), - min_chance_drug = rep(.1, n_drug_ADR_pairs), - avg_duration = rep(5, n_drug_ADR_pairs), - max_chance_drug = rep(NULL, n_drug_ADR_pairs), - prob_guaranteed_exposed = rep(1, n_drug_ADR_pairs), - min_chance = rep(.1, n_drug_ADR_pairs), - max_chance = rep(.4, n_drug_ADR_pairs), - verbose = FALSE) { - - - if (verbose) { +generate_cohort <- function( + n_patients = 100, + simulation_time = 100, + n_drug_ADR_pairs = 50, + risk_model = rep("risk_model_current_use()", n_drug_ADR_pairs), + min_chance_drug = rep(.1, n_drug_ADR_pairs), + avg_duration = rep(5, n_drug_ADR_pairs), + max_chance_drug = rep(NULL, n_drug_ADR_pairs), + prob_guaranteed_exposed = rep(1, n_drug_ADR_pairs), + min_chance = rep(.1, n_drug_ADR_pairs), + max_chance = rep(.4, n_drug_ADR_pairs), + verbose = FALSE +) { + if (verbose) { cat("Generating the patients...\n") pb <- txtProgressBar(min = 0, max = n_patients, style = 3) } - - # generate patients - patients <- lapply(1:n_patients, function(i) { - - guaranteed_exp <- rbinom(n_drug_ADR_pairs, 1, prob_guaranteed_exposed) - + + # generate patients + patients <- lapply(1:n_patients, function(i) { + guaranteed_exp <- rbinom(n_drug_ADR_pairs, 1, prob_guaranteed_exposed) + patient <- generate_patient( simulation_time, n_drug_ADR_pairs, @@ -50,56 +50,59 @@ generate_cohort <- function(n_patients = 100, min_chance, max_chance ) - - if (verbose) { + + if (verbose) { setTxtProgressBar(pb, i) } return(patient) }) - - if (verbose) { - close(pb) + + if (verbose) { + close(pb) cat("DONE generating the patients...\n\nOrganizing the data into matrices...\n") pb <- txtProgressBar(min = 0, max = n_drug_ADR_pairs, style = 3) } - + res <- lapply(1:n_drug_ADR_pairs, function(i) { - drug_history <- matrix(rep(NA, simulation_time * n_patients), nrow = n_patients) + drug_history <- matrix(rep(NA, simulation_time * n_patients), nrow = n_patients) adr_history <- drug_history - + sapply(1:n_patients, function(p) { - #print(patients[[p]][[i]]) + # print(patients[[p]][[i]]) drug_history[p, ] <<- patients[[p]][[i]]$drug_history adr_history[p, ] <<- patients[[p]][[i]]$adr_history }) - if (verbose) { + if (verbose) { setTxtProgressBar(pb, i) } - - list(drug_history = Matrix(drug_history, sparse = TRUE), - adr_history = Matrix(adr_history, sparse = TRUE)) + + list( + drug_history = Matrix(drug_history, sparse = TRUE), + adr_history = Matrix(adr_history, sparse = TRUE) + ) }) - if (verbose) { - close(pb) + if (verbose) { + close(pb) cat("DONE organizing the data into matrices...\n") } - + res$n_patients <- n_patients res$n_drug_ADR_pairs <- n_drug_ADR_pairs res$simulation_time <- simulation_time - + class(res) <- "cohort" return(res) } #' Print function for \code{\link{generate_cohort}} +#' @param x A \code{cohort} object. +#' @param ... Unused. #' @export -print.cohort <- function(cohort) { - +print.cohort <- function(x, ...) { cat("Cohort\n\n") - cat(sprintf(" No. patients:\t\t%d\n", cohort$n_patients)) - cat(sprintf(" No. drug-ADR-pairs:\t%d\n", cohort$n_drug_ADR_pairs)) - cat(sprintf(" No. time points:\t%d\n", cohort$simulation_time)) -} \ No newline at end of file + cat(sprintf(" No. patients:\t\t%d\n", x$n_patients)) + cat(sprintf(" No. drug-ADR-pairs:\t%d\n", x$n_drug_ADR_pairs)) + cat(sprintf(" No. time points:\t%d\n", x$simulation_time)) +} diff --git a/R/generate-drug-ADR-pair.R b/R/generate-drug-ADR-pair.R index 03e4752..d0e6e72 100644 --- a/R/generate-drug-ADR-pair.R +++ b/R/generate-drug-ADR-pair.R @@ -1,31 +1,31 @@ #' Generate a Drug-ADR pair -#' +#' #' Generates the drug- and ADR history -#' +#' #' @param simulation_time The total number of time steps #' @param risk_model One of the risk models #' @param min_chance_drug The probability of the drug being prescribed #' when the drug history and the ADR history have no effect #' @param avg_duration Average number of time points a patient is exposed #' once exposed to the drug (Determines \code{max_chance}) -#' @param max_chance_drug The probability of the ADR when -#' the drug history and the ADR history have the highest +#' @param max_chance_drug The probability of the ADR when +#' the drug history and the ADR history have the highest #' possible effect (Default: \code{NULL}) #' @param guaranteed_exposed If \code{TRUE}, the patient is exposed to the drug #' at least once -#' @param min_chance The probability of the ADR when -#' the drug history has no effect -#' @param max_chance The probability of the ADR when +#' @param min_chance The probability of the ADR when +#' the drug history has no effect +#' @param max_chance The probability of the ADR when #' the drug history has the highest possible effect -#' +#' #' @return A list with -#' \item{\code{drug_history}}{binary vector of the +#' \item{\code{drug_history}}{binary vector of the #' drug history} -#' \item{\code{adr_history}}{binary vector of the +#' \item{\code{adr_history}}{binary vector of the #' ADR history} #' -#' @seealso \code{\link{generate_cohort}} -#' @examples +#' @seealso \code{\link{generate_cohort}} +#' @examples #' drug_ADR_pair <- expard::generate_drug_ADR_pair() #' @export generate_drug_ADR_pair <- function(simulation_time = 100, @@ -34,51 +34,51 @@ generate_drug_ADR_pair <- function(simulation_time = 100, avg_duration = 5, max_chance_drug = NULL, guaranteed_exposed = TRUE, - min_chance = .1, - max_chance = .4) -{ - - - drug_history <- generate_drug_history(simulation_time, min_chance_drug, - avg_duration, max_chance_drug, - guaranteed_exposed) - - - adr_history <- generate_adr_history(drug_history, risk_model, min_chance, max_chance) - + min_chance = .1, + max_chance = .4) { + drug_history <- generate_drug_history( + simulation_time, min_chance_drug, + avg_duration, max_chance_drug, + guaranteed_exposed + ) + + + adr_history <- generate_adr_history(drug_history, risk_model, min_chance, max_chance) + res <- list( drug_history = drug_history, adr_history = adr_history ) - + class(res) <- c(class(res), "drug_ADR_pair") - + return(res) } #' Function for printing a drug-ADR pair +#' @param x A \code{drug_ADR_pair} object. +#' @param ... Unused. #' @export -print.drug_ADR_pair <- function(drug_ADR_pair) { +print.drug_ADR_pair <- function(x, ...) { + simulation_time <- length(x$drug_history) - simulation_time <- length(drug_ADR_pair$drug_history) - cat(sprintf("Drug: ")) - sapply(drug_ADR_pair$drug_history, function(x) { - if (x == 1) { - cat(green(1)) + sapply(x$drug_history, function(x) { + if (x == 1) { + cat(crayon::green(1)) } else { - cat(blue(".")) + cat(crayon::blue(".")) } }) - + cat(sprintf("\nADR: ")) - sapply(drug_ADR_pair$adr_history, function(y) { - if (y == 1) { - cat(red(1)) + sapply(x$adr_history, function(y) { + if (y == 1) { + cat(crayon::red(1)) } else { - cat(blue(".")) + cat(crayon::blue(".")) } }) - + cat(sprintf("\n")) } diff --git a/R/generate-drug-history.R b/R/generate-drug-history.R index f5936f5..0019025 100644 --- a/R/generate-drug-history.R +++ b/R/generate-drug-history.R @@ -1,76 +1,77 @@ #' Generate Drug Prescription History -#' -#' Returns whether or not the drug is prescribed -#' at the next time point (\code{1}) or not (\code{0}). -#' The probability depends on the drug prescriptions, +#' +#' Returns whether or not the drug is prescribed +#' at the next time point (\code{1}) or not (\code{0}). +#' The probability depends on the drug prescriptions, #' the ADR history and the \code{drug_model}. -#' +#' #' @param simulation_time Total number of time points #' @param min_chance The probability of the drug being prescribed #' when the drug history and the ADR history have no effect #' @param avg_duration Average number of time points a patient is exposed #' once exposed to the drug (Determines \code{max_chance}) -#' @param max_chance The probability of the ADR when -#' the drug history and the ADR history have the highest +#' @param max_chance The probability of the ADR when +#' the drug history and the ADR history have the highest #' possible effect (Default: \code{NULL}) #' @param guaranteed_exposed If \code{TRUE}, the patient is exposed to the drug #' at least once -#' +#' @param ... Unused +#' #' @return \code{1} or \code{0} #' @family Update functions -#' @examples -#' generate_drug_history(simulation_time = 10, -#' min_chance = .1, -#' avg_duration = 5 -#' guaranteed_exposed = TRUE) +#' @examples +#' generate_drug_history( +#' simulation_time = 10, +#' min_chance = .1, +#' avg_duration = 5, +#' guaranteed_exposed = TRUE +#' ) #' @export -generate_drug_history <- function(simulation_time = 10, - min_chance, - avg_duration = 5, - max_chance = NULL, - guaranteed_exposed = TRUE, - ...) { - - if (avg_duration < 1) { - stop("avg duration must be at least 1") +generate_drug_history <- function( + simulation_time = 10, + min_chance, + avg_duration = 5, + max_chance = NULL, + guaranteed_exposed = TRUE, + ... +) { + if (avg_duration < 1) { + stop("avg duration must be at least 1") } - - if (is.null(max_chance)) { - max_chance = (avg_duration - 1) / avg_duration + + if (is.null(max_chance)) { + max_chance <- (avg_duration - 1) / avg_duration } - + # determine first time the drug is prescribed by a random sample - if (guaranteed_exposed) { - first <- determine_first_prescription(n_patients = 1, simulation_time, min_chance) - - if (first == simulation_time) { - drug_history <- c(rep(0, simulation_time - 1), 1) + if (guaranteed_exposed) { + first <- determine_first_prescription(n_patients = 1, simulation_time, min_chance) + + if (first == simulation_time) { + drug_history <- c(rep(0, simulation_time - 1), 1) return(drug_history) } - - # initialize the drug and ADR time processes + + # initialize the drug and ADR time processes drug_history <- c(rep(0, first - 1), 1, rep(NA, simulation_time - first)) - + # simulate the remaining time points - for (t in (first+1):simulation_time) { + for (t in (first + 1):simulation_time) { # get the probability of the next time point - prob <- min_chance + (max_chance - min_chance) * drug_history[t-1] - drug_history[t] <- rbinom(1,1,prob) + prob <- min_chance + (max_chance - min_chance) * drug_history[t - 1] + drug_history[t] <- rbinom(1, 1, prob) } - - - } else { - + } else { # determine the first time point - drug_history <- c(rbinom(1,1, min_chance), rep(NA, simulation_time - 1)) - + drug_history <- c(rbinom(1, 1, min_chance), rep(NA, simulation_time - 1)) + # simulate the remaining time points - for (t in 2:simulation_time) { + for (t in 2:simulation_time) { # get the probability of the next time point - prob <- min_chance + (max_chance - min_chance) * drug_history[t-1] - drug_history[t] <- rbinom(1,1,prob) + prob <- min_chance + (max_chance - min_chance) * drug_history[t - 1] + drug_history[t] <- rbinom(1, 1, prob) } } - + return(drug_history) } diff --git a/R/generate-patient.R b/R/generate-patient.R index a8e1a87..9f408aa 100644 --- a/R/generate-patient.R +++ b/R/generate-patient.R @@ -1,36 +1,36 @@ -#' Generate a Patient -#' -#' Generates a patient, which is a collection of different -#' drug-ADR pairs, see function \code{\link{generate_drug_ADR_pair}}. -#' +#' Generate a Patient +#' +#' Generates a patient, which is a collection of different +#' drug-ADR pairs, see function \code{\link{generate_drug_ADR_pair}}. +#' #' @param simulation_time The total number of time steps #' @param n_drug_ADR_pairs Number of drug-ADR pairs simulated -#' @param risk_model Vector with risk models. Each risk model is given as -#' a string, e.g., \code{"risk_model_current_use()"}. The -#' vector must have the length \code{n_drug_ADR_pairs}#' +#' @param risk_model Vector with risk models. Each risk model is given as +#' a string, e.g., \code{"risk_model_current_use()"}. The +#' vector must have the length \code{n_drug_ADR_pairs}#' #' @param min_chance_drug Vector with the probabilities of the drug being prescribed -#' when the drug history and the ADR history have no effect. -#' Must have a length of \code{n_drug_ADR_pairs}. +#' when the drug history and the ADR history have no effect. +#' Must have a length of \code{n_drug_ADR_pairs}. #' @param avg_duration Average number of time points a patient is exposed #' once exposed to the drug (Determines \code{max_chance}) -#' Must have a length of \code{n_drug_ADR_pairs}. -#' @param max_chance_drug The probability of the ADR when -#' the drug history and the ADR history have the highest +#' Must have a length of \code{n_drug_ADR_pairs}. +#' @param max_chance_drug The probability of the ADR when +#' the drug history and the ADR history have the highest #' possible effect (Default: \code{NULL}) -#' Must have a length of \code{n_drug_ADR_pairs}. +#' Must have a length of \code{n_drug_ADR_pairs}. #' @param guaranteed_exposed If \code{TRUE}, the patient is exposed to the drug #' at least once -#' Must have a length of \code{n_drug_ADR_pairs}. -#' @param min_chance The probability of the ADR when +#' Must have a length of \code{n_drug_ADR_pairs}. +#' @param min_chance The probability of the ADR when #' the drug history has no effect -#' Must have a length of \code{n_drug_ADR_pairs}. -#' @param max_chance The probability of the ADR when +#' Must have a length of \code{n_drug_ADR_pairs}. +#' @param max_chance The probability of the ADR when #' the drug history has the highest possible effect -#' Must have a length of \code{n_drug_ADR_pairs}. -#' +#' Must have a length of \code{n_drug_ADR_pairs}. +#' #' @return A list of drug-ADR pairs, see \code{\link{generate_drug_ADR_pair}} #' -#' @seealso \code{\link{generate_cohort}}, \code{\link{generate_drug_ADR_pair}}, \code{\link{generate_drug_history}} +#' @seealso \code{\link{generate_cohort}}, \code{\link{generate_drug_ADR_pair}}, \code{\link{generate_drug_history}} #' @export generate_patient <- function(simulation_time = 100, n_drug_ADR_pairs = 50, @@ -39,38 +39,38 @@ generate_patient <- function(simulation_time = 100, avg_duration = rep(5, n_drug_ADR_pairs), max_chance_drug = rep(NULL, n_drug_ADR_pairs), guaranteed_exposed = rep(TRUE, n_drug_ADR_pairs), - min_chance = rep(.1, n_drug_ADR_pairs), - max_chance = rep(.4, n_drug_ADR_pairs)) { - - res <- lapply(1:n_drug_ADR_pairs, function(i) { - - generate_drug_ADR_pair(simulation_time = simulation_time, - eval( parse(text = risk_model[i]) ), - min_chance_drug[i], - avg_duration[i], - max_chance_drug[i], - guaranteed_exposed[i], - min_chance[i], - max_chance[i]) - }) - + min_chance = rep(.1, n_drug_ADR_pairs), + max_chance = rep(.4, n_drug_ADR_pairs)) { + res <- lapply(1:n_drug_ADR_pairs, function(i) { + generate_drug_ADR_pair( + simulation_time = simulation_time, + eval(parse(text = risk_model[i])), + min_chance_drug[i], + avg_duration[i], + max_chance_drug[i], + guaranteed_exposed[i], + min_chance[i], + max_chance[i] + ) + }) + class(res) <- c(class(res), "patient") return(res) } -#' Function for printing a patient +#' Function for printing a patient +#' @param x A \code{patient} object. +#' @param ... Unused. #' @export -print.patient <- function(patient) { - cat(sprintf("Patient\n")) - - simulation_time - - cat(sprintf("\nNo. of time points: %d\n\n", patient$simulation_time)) - - lapply(1:length(patient), function(i) { +print.patient <- function(x, ...) { + cat(sprintf("Patient\n")) + + cat(sprintf("\nNo. of time points: %d\n\n", x[["simulation_time"]])) + + lapply(1:length(x), function(i) { cat(sprintf("Drug-ADR pair %d\n", i)) - print(patient[[i]]) + print(x[[i]]) }) - + cat(sprintf("\n")) } diff --git a/R/loglikelihood.R b/R/loglikelihood.R index aed1558..41bef5a 100644 --- a/R/loglikelihood.R +++ b/R/loglikelihood.R @@ -1,256 +1,285 @@ #' Negative of the Log-Likelihood Function -#' -#' \code{loglikelihood} returns the negative -#' log-likelihood function, defined as -#' \deqn{\pi = \frac{\exp(\beta_0 + \code{risks}\cdot \beta)}{1 + \exp(\beta_0 + \code{risks}\cdot \beta)}} -#' where \eqn{\pi} is the probability. -#' +#' +#' \code{loglikelihood} returns the negative +#' log-likelihood function, defined as +#' \deqn{\pi = \frac{\exp(\beta_0 + \code{risks}\cdot \beta)}{1 + \exp(\beta_0 + \code{risks}\cdot \beta)}} +#' where \eqn{\pi} is the probability. +#' #' @param betas Vector with two entries: \code{beta0, beta} -#' @param risks Risks determined by the risk model. The risk -#' model was applied to the observed drug prescription +#' @param risks Risks determined by the risk model. The risk +#' model was applied to the observed drug prescription #' history +#' @param adr_history Binary vector with the observed ADR history +#' @param drug_history Binary vector with the observed drug history #' @export loglikelihood <- function(betas, risks, adr_history) { - # extract parameters beta0 <- betas[1] beta <- betas[2] P <- exp(beta0 + risks * beta) / (1 + exp(beta0 + risks * beta)) - -1 * sum( adr_history * log(P) + (1 - adr_history)*log(1 - P)) + -1 * sum(adr_history * log(P) + (1 - adr_history) * log(1 - P)) } #' @export +#' @param past Passed to [risk_model_past()] +#' @rdname loglikelihood loglikelihood_past <- function(param, past, drug_history, adr_history) { - # extract parameters beta0 <- param[1] beta <- param[2] - - risk_model <- expard::risk_model_past(past) - + + risk_model <- risk_model_past(past) + n_patients <- nrow(drug_history) simulation_time <- ncol(drug_history) - + # 'convert' the drug prescriptions. They reflect which period is considered # to have an increased risk risks <- matrix(0, nrow = n_patients, ncol = simulation_time) - - # go over all patients - for (i in 1:n_patients) { - # go over all timepoints + + # go over all patients + for (i in seq_len(n_patients)) { + # go over all timepoints risks[i, ] <- risk_model(drug_history[i, ]) } - - #risks <- Matrix(apply(drug_history, 1, function(d) risk_model(d))) - + + # risks <- Matrix(apply(drug_history, 1, function(d) risk_model(d))) + P <- exp(beta0 + risks * beta) / (1 + exp(beta0 + risks * beta)) - -1 * sum( adr_history * log(P) + (1 - adr_history)*log(1 - P)) + -1 * sum(adr_history * log(P) + (1 - adr_history) * log(1 - P)) } - +#' @param param Vector with parameters. +#' @param freq_table A data frame with the column \code{unique_value}. #' @export -loglikelihood_withdrawal <- function(param, - freq_table) { - +#' @rdname loglikelihood +loglikelihood_withdrawal <- function( + param, + freq_table +) { # extract parameters beta0 <- param[1] beta <- param[2] phi <- param[3] - + # extract parameters beta0 <- param[1] beta <- param[2] phi <- param[3] - + # transform to regular parameters pi0 <- exp(beta0) / (1 + exp(beta0)) pi1 <- exp(beta) / (1 + exp(beta)) rate <- exp(phi) - - # determine the risks given the time_since last exposure and the rate + + # determine the risks given the time_since last exposure and the rate # of the withdrawal model - freq_table <- freq_table %>% mutate( - risk_value = exp(-rate * (unique_value - 1)) + freq_table <- freq_table |> + dplyr::mutate( + risk_value = exp(-rate * (.data$unique_value - 1)) ) - + # the risk when the time_since is 0 (never exposed or currently exposed) # is zero freq_table$risk_value[1] <- 0 - + # determine the log-likelihood given the risks - freq_table <- freq_table %>% rowwise() %>% - mutate(loglikelihood = -1*(n_adr*log((pi1 - pi0)*risk_value + pi0) + - n_no_adr * log(1 - (pi1 - pi0)*risk_value - pi0))) - + freq_table <- freq_table |> + dplyr::rowwise() |> + dplyr::mutate( + loglikelihood = -1 * (.data$n_adr * log((pi1 - pi0) * .data$risk_value + pi0) + + .data$n_no_adr * log(1 - (pi1 - pi0) * .data$risk_value - pi0)) + ) + sum(freq_table$loglikelihood) } #' @export -loglikelihood_delayed <- function(param, - freq_table) { - +#' @rdname loglikelihood +loglikelihood_delayed <- function( + param, + freq_table +) { # extract parameters beta0 <- param[1] beta <- param[2] mu_log <- param[3] sigma_log <- param[4] - + # transform to regular parameters pi0 <- exp(beta0) / (1 + exp(beta0)) pi1 <- exp(beta) / (1 + exp(beta)) mu <- exp(mu_log) sigma <- exp(sigma_log) - + # to make sure that the highest value is indeed 1 - normalizing_factor <- dnorm(mu, mu, sigma) - - # determine the risks given the time_since last exposure and the rate + normalizing_factor <- stats::dnorm(mu, mu, sigma) + + # determine the risks given the time_since last exposure and the rate # of the withdrawal model - freq_table <- freq_table %>% mutate( - risk_value = dnorm(unique_value, mu, sigma) / normalizing_factor - ) - + freq_table <- freq_table |> + dplyr::mutate( + risk_value = stats::dnorm(unique_value, mu, sigma) / normalizing_factor + ) + # the risk when the time_since is 0 (never exposed or currently exposed) # is zero freq_table$risk_value[1] <- 0 - + # determine the log-likelihood given the risks - freq_table <- freq_table %>% rowwise() %>% - mutate(loglikelihood = -1*(n_adr*log((pi1 - pi0)*risk_value + pi0) + - n_no_adr * log(1 - (pi1 - pi0)*risk_value - pi0))) - + freq_table <- freq_table |> + dplyr::rowwise() |> + dplyr::mutate( + loglikelihood = -1 * (.data$n_adr * log((pi1 - pi0) * .data$risk_value + pi0) + + .data$n_no_adr * log(1 - (pi1 - pi0) * .data$risk_value - pi0)) + ) + sum(freq_table$loglikelihood) } - - - - #' @export -loglikelihood_decaying <- function(param, - freq_table) { - +#' @rdname loglikelihood +loglikelihood_decaying <- function( + param, + freq_table +) { + # extract parameters beta0 <- param[1] beta <- param[2] rate_log <- param[3] - + # transform to regular parameters pi0 <- exp(beta0) / (1 + exp(beta0)) pi1 <- exp(beta) / (1 + exp(beta)) rate <- exp(rate_log) - - # determine the risks given the time_since last exposure and the rate + + # determine the risks given the time_since last exposure and the rate # of the withdrawal model - freq_table <- freq_table %>% mutate( - #risk_value = exp(-rate * (unique_value - 1)) - risk_value = exp(-rate * (unique_value - 1)) - ) - + freq_table <- freq_table |> + dplyr::mutate( + # risk_value = exp(-rate * (unique_value - 1)) + risk_value = exp(-rate * (.data$unique_value - 1)) + ) + # the risk when the time_since is 0 (never exposed or currently exposed) # is zero freq_table$risk_value[1] <- 0 - + # determine the log-likelihood given the risks - freq_table <- freq_table %>% rowwise() %>% - mutate(loglikelihood = -1*(n_adr*log((pi1 - pi0)*risk_value + pi0) + - n_no_adr * log(1 - (pi1 - pi0)*risk_value - pi0))) - + freq_table <- freq_table |> + dplyr::rowwise() |> + dplyr::mutate( + loglikelihood = -1 * (.data$n_adr * log((pi1 - pi0) * .data$risk_value + pi0) + + .data$n_no_adr * log(1 - (pi1 - pi0) * .data$risk_value - pi0)) + ) + sum(freq_table$loglikelihood) } - - - #' @export -loglikelihood_delayed_decaying <- function(param, - freq_table) { - +#' @rdname loglikelihood +loglikelihood_delayed_decaying <- function( + param, + freq_table +) { + # extract parameters beta0 <- param[1] beta <- param[2] mu_log <- param[3] sigma_log <- param[4] rate_log <- param[5] - + # transform to regular parameters pi0 <- exp(beta0) / (1 + exp(beta0)) pi1 <- exp(beta) / (1 + exp(beta)) mu <- exp(mu_log) sigma <- exp(sigma_log) rate <- exp(rate_log) - - #combination <- delay(drug_history) + decay(drug_history) - #combination / max(combination) - + + # combination <- delay(drug_history) + decay(drug_history) + # combination / max(combination) + # to make sure that the highest value is indeed 1 - normalizing_factor <- dnorm(mu, mu, sigma) - - # determine the risks given the time_since last exposure and the rate + normalizing_factor <- stats::dnorm(mu, mu, sigma) + + # determine the risks given the time_since last exposure and the rate # of the withdrawal model - freq_table <- freq_table %>% mutate( - #risk_value = exp(-rate * (unique_value - 1)) - risk_value_delayed = dnorm(unique_value, mu, sigma) / normalizing_factor, - risk_value_decaying = exp(-rate * (unique_value - 1)), - risk_value = (risk_value_delayed + risk_value_decaying) / max(risk_value_delayed + risk_value_decaying) - ) - + freq_table <- freq_table |> + dplyr::mutate( + # risk_value = exp(-rate * (unique_value - 1)) + risk_value_delayed = stats::dnorm(.data$unique_value, mu, sigma) / normalizing_factor, + risk_value_decaying = exp(-rate * (.data$unique_value - 1)), + risk_value = (.data$risk_value_delayed + .data$risk_value_decaying) / + max(.data$risk_value_delayed + .data$risk_value_decaying) + ) + # the risk when the time_since is 0 (never exposed or currently exposed) # is zero freq_table$risk_value[1] <- 0 - + # determine the log-likelihood given the risks - freq_table <- freq_table %>% rowwise() %>% - mutate(loglikelihood = -1*(n_adr*log((pi1 - pi0)*risk_value + pi0) + - n_no_adr * log(1 - (pi1 - pi0)*risk_value - pi0))) - + freq_table <- freq_table |> + dplyr::rowwise() |> + dplyr::mutate( + loglikelihood = -1 * (.data$n_adr * log((pi1 - pi0) * .data$risk_value + pi0) + + .data$n_no_adr * log(1 - (pi1 - pi0) * .data$risk_value - pi0)) + ) + sum(freq_table$loglikelihood) } -#risk_model_long_term <- function(rate, delay) +# risk_model_long_term <- function(rate, delay) #' @export -loglikelihood_long_term <- function(param, - freq_table) { - +#' @rdname loglikelihood +loglikelihood_long_term <- function( + param, + freq_table +) { # extract parameters beta0 <- param[1] beta <- param[2] rate_log <- param[3] delay_log <- param[4] - + # transform to regular parameters pi0 <- exp(beta0) / (1 + exp(beta0)) pi1 <- exp(beta) / (1 + exp(beta)) rate <- exp(rate_log) delay <- exp(delay_log) - - # determine the risks given the time_since last exposure and the rate + + # determine the risks given the time_since last exposure and the rate # of the withdrawal model - freq_table <- freq_table %>% mutate( - #risk_value = exp(-rate * (unique_value - 1)) - risk_value = 1 / (1 + exp(-rate * (unique_value - delay))) + freq_table <- freq_table |> + dplyr::mutate( + # risk_value = exp(-rate * (unique_value - 1)) + risk_value = 1 / (1 + exp(-rate * (.data$unique_value - delay))) ) - + # the risk when the time_since is 0 (never exposed or currently exposed) # is zero freq_table$risk_value[1] <- 0 - + # determine the log-likelihood given the risks - freq_table <- freq_table %>% rowwise() %>% - mutate(loglikelihood = -1*(n_adr*log((pi1 - pi0)*risk_value + pi0) + - n_no_adr * log(1 - (pi1 - pi0)*risk_value - pi0))) - + freq_table <- freq_table |> + dplyr::rowwise() |> + dplyr::mutate( + loglikelihood = -1 * (.data$n_adr * log((pi1 - pi0) * .data$risk_value + pi0) + + .data$n_no_adr * log(1 - (pi1 - pi0) * .data$risk_value - pi0)) + ) + sum(freq_table$loglikelihood) } diff --git a/R/plot-fit.R b/R/plot-fit.R index 1fdbc61..e761aa1 100644 --- a/R/plot-fit.R +++ b/R/plot-fit.R @@ -1,60 +1,62 @@ -#' Plot the Fit -#' -#' Plots the BIC for the different risk models that were fitted by the -#' function \code{\link{fit_all_models}}. -#' -#' @param fit The fit -#' @param xlab The x-label -#' @param past_values If not \code{NULL}, a select number of values for past are +#' Plot the Fit +#' +#' Plots the BIC for the different risk models that were fitted by the +#' function [fit_all_models()]. +#' +#' @param fit The fit +#' @param x_label The x-label for the plot +#' @param title The plot title +#' @param y_range Used as minimum for the y axis. Guessed if not provided. +#' @param past_values If not `NULL`, a select number of values for past are #' used for the plot -#' -#' @return ggplot +#' +#' @return ggplot #' @export -plot_fit <- function(fit, - x_label = "model", - title = "", - y_range = NULL, +plot_fit <- function(fit, + x_label = "model", + title = "", + y_range = NULL, past_values = NULL) { - - - # if one run the fit_all_models in parallel, process the data - if('past-use(1)' %in% fit$model) { + # if one run the fit_all_models in parallel, process the data + if ("past-use(1)" %in% fit$model) { simulation_time <- fit$simulation_time[1] - - past_models <- sprintf('past-use(%d)', 1:(simulation_time-1)) - + + past_models <- sprintf("past-use(%d)", 1:(simulation_time - 1)) + fit$model <- sapply(1:nrow(fit), function(i) { - if(grepl('past-use', fit$model[i], fixed = TRUE)) { - return('past-use') + if (grepl("past-use", fit$model[i], fixed = TRUE)) { + return("past-use") } else { fit$model[i] } }) } - + # Use only the 'past-use' models for which the past parameter falls in the given range if (!is.null(past_values)) { - fit <- fit %>% filter(model != 'past-use' | past %in% past_values) + fit <- fit |> dplyr::filter(model != "past-use" | past %in% past_values) } # get the best BIC fit for each model - best_fit <- fit %>% group_by(model) %>% - filter(BIC == min(BIC)) %>% - arrange(past) %>% - filter(row_number() == 1) %>% - arrange(BIC) + best_fit <- fit |> + dplyr::group_by(model) |> + dplyr::slice_min(.data$BIC) |> + #dplyr::filter(BIC == min(BIC)) |> + dplyr::arrange(past) |> + dplyr::filter(dplyr::row_number() == 1) |> + dplyr::arrange(.data$BIC) # get the overall minimum and maximum BIC value min_BIC <- min(best_fit$BIC) max_BIC <- max(best_fit$BIC) - + if (is.null(y_range)) { - y_range <- c(min_BIC,max_BIC) + y_range <- c(min_BIC, max_BIC) } old_model_label <- c("past-use", "current-use", "no-association") new_model_label <- c("past use", "current use", "no association") - + # Use sapply to replace each occurrence in the input_vector best_fit$model <- sapply(best_fit$model, function(x) { for (i in seq_along(old_model_label)) { @@ -62,23 +64,29 @@ plot_fit <- function(fit, } return(x) }) - + # plot just the best fit - ggplot(best_fit) + - geom_bar(aes(x = reorder(model, BIC), y = BIC), stat="identity") + - coord_cartesian(ylim=y_range) + - ggtitle(title) + - #scale_y_continuous(expand = expansion(mult = c(0.1, .1))) + #expand = c(0, 100)) + - theme_bw() + - theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) + - xlab(x_label) - + ggplot2::ggplot(best_fit) + + ggplot2::geom_bar( + ggplot2::aes( + x = stats::reorder(.data$model, .data$BIC), + y = .data$BIC + ), + stat = "identity") + + ggplot2::coord_cartesian(ylim = y_range) + + ggplot2::labs(title = title, x = x_label) + + # scale_y_continuous(expand = expansion(mult = c(0.1, .1))) + #expand = c(0, 100)) + + ggplot2::theme_bw() + + ggplot2::theme( + axis.text.x = ggplot2::element_text(angle = 45, vjust = 1, hjust = 1) + ) + # plot just the best fit # ggplot(best_fit) + # geom_bar(aes(x = reorder(model, BIC), y = BIC), stat="identity") + - # coord_cartesian(ylim=y_range) + - # scale_y_continuous(expand = expansion(mult = c(0.1, .1))) + #expand = c(0, 100)) + + # coord_cartesian(ylim=y_range) + + # scale_y_continuous(expand = expansion(mult = c(0.1, .1))) + #expand = c(0, 100)) + # theme_bw() + # theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) + - # xlab("model") + # xlab("model") } diff --git a/R/plot-risk.R b/R/plot-risk.R index de8c79b..5ae9872 100644 --- a/R/plot-risk.R +++ b/R/plot-risk.R @@ -1,111 +1,131 @@ #' Plot Risk -#' -#' Plots the risk function's behavior for -#' a given drug prescription history. -#' The \eqn{x}-axis denote the -#' drug prescriptions and the \eqn{y}-axis represent the -#' risk level, i.e., \code{1} is maximal risk, \code{0} +#' +#' Plots the risk function's behavior for +#' a given drug prescription history. +#' The \eqn{x}-axis denote the +#' drug prescriptions and the `y`-axis represent the +#' risk level, i.e., `1` is maximal risk, `0` #' minimal risk. -#' -#' @param drug_history Binary vector denoting the -#' drug prescription history. -#' (Default: \code{0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0}) -#' @param risk_model One of the risk models -#' @param simulation_time If not \code{NULL}, total number of time points, i.e., -#' \code{0 0 0 0 1 1 1 1 1 1 0 0 0 0 ...}. (Default: \code{NULL}) +#' +#' @param drug_history Binary vector denoting the +#' drug prescription history. +#' (Default: `0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0`) +#' @param risk_model One of the risk models +#' @param simulation_time If not `NULL`, total number of time points, i.e., +#' `0 0 0 0 1 1 1 1 1 1 0 0 0 0 ...`. (Default: `NULL`) #' @param title Title of the plot -#' @param ylim The limits of the y-axis: \code{c(ymin, ymax)} -#' (Default: \code{c(0,1)}) -#' @param shaded_area If \code{TRUE}, periods in which drugs were -#' prescribed are shaded in a gray tone. Otherwise, -#' the drug prescription periods are denoted by -#' vertical dashed red lines (Default: \code{TRUE}) -#' @param fill Color used for the shaded area (Default: \code{black}) -#' @param alpha Alpha value for shaded area (Default: \code{.3}) -#' -#' @return A \code{ggplot2} plot -#' @examples +#' @param ylim The limits of the y-axis: `c(ymin, ymax)` +#' (Default: `c(0,1)`) +#' @param shaded_area If `TRUE`, periods in which drugs were +#' prescribed are shaded in a gray tone. Otherwise, +#' the drug prescription periods are denoted by +#' vertical dashed red lines (Default: `TRUE`) +#' @param fill Color used for the shaded area (Default: `black`) +#' @param alpha Alpha value for shaded area (Default: `.3`) +#' +#' @return A [ggplot2] plot +#' @examples #' drug_history <- c(rep(0, 4), rep(1, 6), rep(0, 10)) -#' risk_model <- risk_model_immediate() -#' +#' risk_model <- risk_model_withdrawal(rate = 3) +#' #' # create the plot -#' p <- plot_risk(drug_history, -#' risk_model, -#' title = "Direct effect model") +#' p <- plot_risk(drug_history, +#' risk_model, +#' title = "Direct effect model" +#' ) #' p #' @export -plot_risk <- function(drug_history = c(rep(0, 4), rep(1, 6), rep(0, 10)), - risk_model = risk_model_immediate(), - simulation_time = NULL, - title = "", - ylim = c(0,1), - shaded_area = TRUE, - fill = "black", - alpha = 0.3) { - - if (!is.null(simulation_time)) { +plot_risk <- function( + drug_history = c(rep(0, 4), rep(1, 6), rep(0, 10)), + risk_model = risk_model_decaying(3), + simulation_time = NULL, + title = "", + ylim = c(0, 1), + shaded_area = TRUE, + fill = "black", + alpha = 0.3 +) { + + if (!is.null(simulation_time)) { if (simulation_time < 10) { stop("simulation time must be at least 10") } - drug_history <- c(rep(0,4), rep(1,6), rep(0, simulation_time - 10)) + drug_history <- c(rep(0, 4), rep(1, 6), rep(0, simulation_time - 10)) } - - # determine the risks given the drug prescription history + + # determine the risks given the drug prescription history # and the risk model given by risk_model risks <- risk_model(drug_history) - - # create a dataset with the time points, the drug prescriptions + + # create a dataset with the time points, the drug prescriptions # and the risks - data <- data.frame( - t = 1:length(drug_history), + xdf <- data.frame( + t = 1:length(drug_history), drug = drug_history, risk = risks ) - + # determine the time points when the drug prescriptions changes from # "not prescribed" to "prescribed" and the other way around changes <- which(diff(drug_history) != 0) # if drug is prescribed at the first time point, add it to changes - if (drug_history[1] == 1) { - changes <- c(0, changes) + if (drug_history[1] == 1) { + changes <- c(0, changes) } # if drug is prescribed at last time point, add it to changes - if (tail(drug_history, 1) == 1) { - changes <- c(changes, length(drug_history)) + if (utils::tail(drug_history, 1) == 1) { + changes <- c(changes, length(drug_history)) } - + # create a data frame for the change points on the x-axis. Note # that we set it off by + 0.5 so that it falls in the middle - change_points <- data.frame( changes = changes + 0.5 ) - + change_points <- data.frame(changes = changes + 0.5) + # plot the risk over time - p <- ggplot() + - geom_point(data = data, mapping = aes(x = t, y = risks)) + - xlab("time (t)") + - ylab("risk level") + - scale_x_continuous(limits = c(0.45,length(drug_history)+.55), expand = c(0, 0)) + - scale_y_continuous(limits = c(0,1), expand = c(.01, .01)) + - ggtitle(title) - + p <- ggplot2::ggplot() + + ggplot2::geom_point(data = xdf, mapping = ggplot2::aes(x = t, y = risks)) + + ggplot2::scale_x_continuous(limits = c(0.45, length(drug_history) + .55), expand = c(0, 0)) + + ggplot2::scale_y_continuous(limits = c(0, 1), expand = c(.01, .01)) + + ggplot2::labs( + title = title, + x = "time (t)", + y = "Risk Level" + ) + # add a shaded area when the patient is prescribed the drug - if (shaded_area) { + if (shaded_area) { # number of periods a person was prescribed the drug n_drug_periods <- nrow(change_points) / 2 - - if (n_drug_periods > 0) { - temp <- data.frame(xmin = change_points[seq(1, nrow(change_points), by = 2), 1], - xmax = change_points[seq(2, nrow(change_points), by = 2), 1]) - p <- p + - geom_rect(data = temp, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf), alpha = alpha, fill = fill) - } - } else { - p <- p + geom_vline(data = change_points, aes(xintercept = changes), linetype='dashed', color = "red") + if (n_drug_periods > 0) { + temp <- data.frame( + xmin = change_points[seq(1, nrow(change_points), by = 2), 1], + xmax = change_points[seq(2, nrow(change_points), by = 2), 1] + ) + p <- p + + ggplot2::geom_rect( + data = temp, + ggplot2::aes(xmin = .data$xmin, xmax = .data$xmax, ymin = -Inf, ymax = Inf), + alpha = alpha, + fill = fill + ) + } + } else { + p <- p + ggplot2::geom_vline( + data = change_points, + ggplot2::aes(xintercept = changes), + linetype = "dashed", + color = "red" + ) } - + p <- p + - theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), - panel.background = element_blank(), axis.line = element_line(colour = "black")) - + ggplot2::theme( + panel.grid.major = ggplot2::element_blank(), + panel.grid.minor = ggplot2::element_blank(), + panel.background = ggplot2::element_blank(), + axis.line = ggplot2::element_line(colour = "black") + ) + return(p) -} \ No newline at end of file +} diff --git a/R/risk-models.R b/R/risk-models.R index bd48330..7a04fbd 100644 --- a/R/risk-models.R +++ b/R/risk-models.R @@ -1,359 +1,327 @@ ############################################## -# risk-models.R +# risk-models.R # -# Contains all the risk models. +# Contains all the risk models. # They model how the risk of suffering the ADR # changes with the history of drug history -# of the patient. -# The risk models return values between 0 and -# 1. Zero is minimal risk, 1 is full risk. +# of the patient. +# The risk models return values between 0 and +# 1. Zero is minimal risk, 1 is full risk. ############################################## -# -risk_models <- c('no-association', - 'current-use', - 'past-use', - 'withdrawal', - 'delayed', - 'decaying', - 'delayed+decaying', - 'long-term') +# +risk_models <- c( + "no-association", + "current-use", + "past-use", + "withdrawal", + "delayed", + "decaying", + "delayed+decaying", + "long-term" +) #' Risk Model 'No Association' -#' -#' A risk model reflects how the probability of +#' +#' A risk model reflects how the probability of #' suffering the ADR changes with the drug exposures -#' of a patient. It returns \code{0} when the drug -#' prescription history has no effect, and \code{1} -#' when the patient is at maximal risk. +#' of a patient. It returns \code{0} when the drug +#' prescription history has no effect, and \code{1} +#' when the patient is at maximal risk. #' In this case, the drug has no effect on the ADR #' what so ever. -#' +#' #' @return A risk model #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' risk_model <- risk_model_no_effect() -#' risk_model() +#' risk_model <- risk_model_no_effect() +#' risk_model() #' # -> 0 #' @export -risk_model_no_association <- function() { - function(drug_history, ...) { +#' @rdname risk_models +risk_model_no_association <- function() { + function(drug_history, ...) { rep(0, length(drug_history)) } } #' Risk Model 'Immediate' -#' -#' A risk model reflects how the probability of +#' +#' A risk model reflects how the probability of #' suffering the ADR changes with the drug exposures -#' of a patient. It returns \code{0} when the drug -#' prescription history has no effect, and \code{1} -#' when the patient is at maximal risk. -#' In this case, the probability of the ADR +#' of a patient. It returns \code{0} when the drug +#' prescription history has no effect, and \code{1} +#' when the patient is at maximal risk. +#' In this case, the probability of the ADR #' is maximal only when the patient is currently #' exposed. -#' -#' @return A risk model +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' risk_model <- risk_model_immediate() -#' risk_model(drug_history) +#' risk_model <- risk_model_withdrawal(rate = 3) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_current_use <- function() { - function(drug_history, ...) { + function(drug_history, ...) { return(drug_history) } } #' Risk Model 'Withdrawal' -#' -#' A risk model reflects how the probability of +#' +#' A risk model reflects how the probability of #' suffering the ADR changes with the drug exposures -#' of a patient. It returns \code{0} when the drug -#' prescription history has no effect, and \code{1} +#' of a patient. It returns \code{0} when the drug +#' prescription history has no effect, and \code{1} #' when the patient is at maximal risk. #' In this case, once the patient is no longer exposed -#' to the drug, the probability of the ADR peaks -#' and then dissipates exponentially. +#' to the drug, the probability of the ADR peaks +#' and then dissipates exponentially. #' Let \eqn{\tau} be the number of time points since #' the patient was prescribed the drug last. The return -#' value is the given by -#' \deqn{\exp(-\gamma \cdot (\tau - 1))} +#' value is the given by +#' \deqn{\exp(-\gamma \cdot (\tau - 1))} #' where \eqn{\gamma} is \code{rate}. -#' -#' @param rate The rate with which the risk dissipates -#' -#' @return A risk model +#' +#' @param past Reference time point > 0. +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' -#' risk_model <- risk_model_withdrawal(rate = 1.2) -#' risk_model(drug_history) +#' +#' risk_model <- risk_model_past(past = 2) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_past <- function(past) { - # check correctness input - if (past <= 0) { - stop("past should be > 0") + if (past <= 0) { + stop("past should be > 0") } - - function(drug_history, ...) { - - simulation_time <- length(drug_history) - - sapply(1:simulation_time, function(t) { - as.numeric( any(drug_history[max(1,t-past):t] != 0)) + + function(drug_history, ...) { + simulation_time <- length(drug_history) + + sapply(1:simulation_time, function(t) { + as.numeric(any(drug_history[max(1, t - past):t] != 0)) }) } } - - - - #' Risk Model 'Withdrawal' -#' -#' A risk model reflects how the probability of +#' +#' A risk model reflects how the probability of #' suffering the ADR changes with the drug exposures -#' of a patient. It returns \code{0} when the drug -#' prescription history has no effect, and \code{1} +#' of a patient. It returns \code{0} when the drug +#' prescription history has no effect, and \code{1} #' when the patient is at maximal risk. #' In this case, once the patient is no longer exposed -#' to the drug, the probability of the ADR peaks -#' and then dissipates exponentially. +#' to the drug, the probability of the ADR peaks +#' and then dissipates exponentially. #' Let \eqn{\tau} be the number of time points since #' the patient was prescribed the drug last. The return -#' value is the given by -#' \deqn{\exp(-\gamma \cdot (\tau - 1))} +#' value is the given by +#' \deqn{\exp(-\gamma \cdot (\tau - 1))} #' where \eqn{\gamma} is \code{rate}. -#' -#' @param rate The rate with which the risk dissipates -#' -#' @return A risk model +#' +#' @param duration The duration to check against. +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' -#' risk_model <- risk_model_withdrawal(rate = 1.2) -#' risk_model(drug_history) +#' +#' risk_model <- risk_model_withdrawal(rate = 1.2) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_duration <- function(duration) { - # check correctness input - if (duration <= 0) { - stop("past should be > 0") + if (duration <= 0) { + stop("duration should be > 0") } - - function(drug_history, ...) { - - simulation_time <- length(drug_history) - - sapply(1:simulation_time, function(t) { - as.numeric( sum(drug_history[1:t]) >= duration ) + + function(drug_history, ...) { + simulation_time <- length(drug_history) + + sapply(1:simulation_time, function(t) { + as.numeric(sum(drug_history[1:t]) >= duration) }) } } - - - - - - - - - #' Risk Model 'Withdrawal' -#' -#' A risk model reflects how the probability of +#' +#' A risk model reflects how the probability of #' suffering the ADR changes with the drug exposures -#' of a patient. It returns \code{0} when the drug -#' prescription history has no effect, and \code{1} +#' of a patient. It returns \code{0} when the drug +#' prescription history has no effect, and \code{1} #' when the patient is at maximal risk. #' In this case, once the patient is no longer exposed -#' to the drug, the probability of the ADR peaks -#' and then dissipates exponentially. +#' to the drug, the probability of the ADR peaks +#' and then dissipates exponentially. #' Let \eqn{\tau} be the number of time points since #' the patient was prescribed the drug last. The return -#' value is the given by -#' \deqn{\exp(-\gamma \cdot (\tau - 1))} +#' value is the given by +#' \deqn{\exp(-\gamma \cdot (\tau - 1))} #' where \eqn{\gamma} is \code{rate}. -#' +#' #' @param rate The rate with which the risk dissipates -#' -#' @return A risk model +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' -#' risk_model <- risk_model_withdrawal(rate = 1.2) -#' risk_model(drug_history) +#' +#' risk_model <- risk_model_withdrawal(rate = 1.2) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_withdrawal <- function(rate) { - # check correctness input - if (rate <= 0) { - stop("rate should be > 0") + if (rate <= 0) { + stop("rate should be > 0") } - - function(drug_history, ...) { - + + function(drug_history, ...) { simulation_time <- length(drug_history) - + # never took the drug - if (sum(drug_history) == 0) { + if (sum(drug_history) == 0) { return(rep(0, simulation_time)) } - - - sapply(1:simulation_time, function(t) { + + + sapply(1:simulation_time, function(t) { # currently exposed or did not take the drug yet - if (drug_history[t] == 1 || sum(drug_history[1:t]) == 0) { - return(0) + if (drug_history[t] == 1 || sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - max(which(drug_history[1:t] == 1)) - return(exp(-rate * (time_steps_ago - 1))) + time_steps_ago <- t - max(which(drug_history[1:t] == 1)) + return(exp(-rate * (time_steps_ago - 1))) } }) } } - - - #' Risk Model 'Delayed' -#' -#' @param rate The rate with which the risk dissipates -#' -#' @return A risk model +#' +#' @param mu,sigma The parameters to [dnorm()] used to model the risk. +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' -#' risk_model <- risk_model_withdrawal(rate = 1.2) -#' risk_model(drug_history) +#' +#' risk_model <- risk_model_delayed(5, 1) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_delayed <- function(mu, sigma) { - # check correctness input - if (mu <= 0) { + if (mu <= 0) { mu <- 1e-10 - #stop("mu should be > 0") + # stop("mu should be > 0") } - - if (sigma <= 0) { - stop("sigma should be > 0") + + if (sigma <= 0) { + stop("sigma should be > 0") } - + # to make sure that the highest value is indeed 1 normalizing_factor <- dnorm(mu, mu, sigma) - - function(drug_history, ...) { - + + function(drug_history, ...) { simulation_time <- length(drug_history) - + # never took the drug - if (sum(drug_history) == 0) { + if (sum(drug_history) == 0) { return(rep(0, simulation_time)) } - - - sapply(1:simulation_time, function(t) { + + + sapply(1:simulation_time, function(t) { # currently exposed or did not take the drug yet - if (sum(drug_history[1:t]) == 0) { - return(0) + if (sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - min(which(drug_history[1:t] == 1)) - return(dnorm(time_steps_ago, mu, sigma) / normalizing_factor) + time_steps_ago <- t - min(which(drug_history[1:t] == 1)) + return(dnorm(time_steps_ago, mu, sigma) / normalizing_factor) } }) } } - - - - - - - - #' Risk Model 'Decaying' -#' +#' #' @param rate The rate with which the risk dissipates -#' -#' @return A risk model +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0) -#' -#' risk_model <- risk_model_withdrawal(rate = 1.2) -#' risk_model(drug_history) +#' +#' risk_model <- risk_model_decaying(rate = 1.2) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_decaying <- function(rate) { - # check correctness input - if (rate <= 0) { - stop("rate should be > 0") + if (rate <= 0) { + stop("rate should be > 0") } - - #normalizing_factor <- exp(-rate * (time_steps_ago - 1)) - - function(drug_history, ...) { - + + # normalizing_factor <- exp(-rate * (time_steps_ago - 1)) + + function(drug_history, ...) { simulation_time <- length(drug_history) - + # never took the drug - if (sum(drug_history) == 0) { + if (sum(drug_history) == 0) { return(rep(0, simulation_time)) } - - - sapply(1:simulation_time, function(t) { + + + sapply(1:simulation_time, function(t) { # did not take the drug yet - if (sum(drug_history[1:t]) == 0) { - return(0) + if (sum(drug_history[1:t]) == 0) { + return(0) } else { - time_steps_ago = t - min(which(drug_history[1:t] == 1)) - return(exp(-rate * time_steps_ago)) + time_steps_ago <- t - min(which(drug_history[1:t] == 1)) + return(exp(-rate * time_steps_ago)) } }) } } - #' @export +#' @rdname risk_models risk_model_delayed_decaying <- function(mu, sigma, rate) { - # check correctness input - if (rate <= 0) { - stop("rate should be > 0") + if (rate <= 0) { + stop("rate should be > 0") } - - if (mu <= 0) { + + if (mu <= 0) { mu <- 1e-10 - #stop("mu should be > 0") - } - - if (sigma <= 0) { + # stop("mu should be > 0") + } + + if (sigma <= 0) { stop("sigma should be > 0") } - + delay <- risk_model_delayed(mu, sigma) decay <- risk_model_decaying(rate) - - #normalizing_factor <- exp(-rate * (time_steps_ago - 1)) - - function(drug_history, ...) { + + # normalizing_factor <- exp(-rate * (time_steps_ago - 1)) + + function(drug_history, ...) { if (sum(drug_history) == 0) { return(drug_history) } @@ -363,53 +331,49 @@ risk_model_delayed_decaying <- function(mu, sigma, rate) { } - - - #' Risk Model 'Long Time After' -#' -#' A risk model reflects how the probability of +#' +#' A risk model reflects how the probability of #' suffering the ADR changes with the drug exposures -#' of a patient. It returns \code{0} when the drug -#' prescription history has no effect, and \code{1} +#' of a patient. It returns \code{0} when the drug +#' prescription history has no effect, and \code{1} #' when the patient is at maximal risk. #' In this case, the risk of the ADR increases -#' only after a certain moment in time before it +#' only after a certain moment in time before it #' reaches the maximal risk. #' Let \eqn{t_0} be the time point that the drug #' was prescribed for the first time, and \eqn{\delta} #' be the number of time points since first description -#' that the function returns 0.5 ("half way"). The -#' return value is -#' \deqn{1 / (1 + \exp(-\gamma \cdot (t_0 - \delta)))} -#' where \eqn{\gamma} is \code{rate}. Note that this -#' is a sigmoid function. -#' +#' that the function returns 0.5 ("half way"). The +#' return value is +#' \deqn{1 / (1 + \exp(-\gamma \cdot (t_0 - \delta)))} +#' where \eqn{\gamma} is \code{rate}. Note that this +#' is a sigmoid function. +#' #' @param rate The rate with which the risk increases #' @param delay How long it takes before the risk is .5 -#' -#' @return A risk model +#' #' @family Risk models -#' @examples +#' @examples #' drug_history <- c(1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1) -#' -#' risk_model <- risk_model_long_time_after(rate = .5, delay = 9) -#' risk_model(drug_history) +#' +#' risk_model <- risk_model_long_time_after(rate = .5, delay = 9) +#' risk_model(drug_history) #' @export +#' @rdname risk_models risk_model_long_term <- function(rate, delay) { - function(drug_history, ...) { - + function(drug_history, ...) { simulation_time <- length(drug_history) - + # moment of first prescription sapply(1:simulation_time, function(t) { - # if case the drug was never prescribed + # if case the drug was never prescribed if (sum(drug_history[1:t]) == 0) { return(0) } else { # moment of first prescription - time_since_first_prescription = t - min(which(drug_history[1:t] == 1)) - + time_since_first_prescription <- t - min(which(drug_history[1:t] == 1)) + # use a sigmoid function to determine the effect return(1 / (1 + exp(-rate * (time_since_first_prescription - delay)))) } diff --git a/R/zzz.R b/R/zzz.R deleted file mode 100644 index 5d3d1a7..0000000 --- a/R/zzz.R +++ /dev/null @@ -1,7 +0,0 @@ -#' \code{expard}: A package for simulating electronic -#' health care data and fitting models -#' -#' @docType package -#' @author Louis Dijkstra -#' @name expard -NULL diff --git a/README.Rmd b/README.Rmd new file mode 100644 index 0000000..f16662b --- /dev/null +++ b/README.Rmd @@ -0,0 +1,102 @@ +--- +output: github_document +--- + + + +```{r, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>", + fig.path = "man/figures/README-", + out.width = "100%" +) +``` + +# expard + + +[![R-CMD-check](https://github.com/bips-hb/expard/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/bips-hb/expard/actions/workflows/R-CMD-check.yaml) + + +`expard` constitutes an `R` package encompassing two primary functionalities: + +1. It serves as a simulator for electronic healthcare data, enabling the simulation of extensive patient populations observed across multiple time points. Leveraging `R`'s functional programming features, the package facilitates the straightforward specification of intricate relationships between drug exposures and adverse drug reactions (ADRs). These relationships may be contingent on various patient attributes such as sex, age, region, among others. + +2. The package includes a methodology designed to fit eight exposure models outlined in the associated paper to electronic healthcare data. + +## Usage + +### Simulator + +The main function of the package is `generate_cohort` (see `?generate_cohort`). For example, + +```{r} +library(expard) + +n_drug_ADR_pairs <- 50 + +generate_cohort( + n_patients = 100, + simulation_time = 100, + n_drug_ADR_pairs = n_drug_ADR_pairs, + risk_model = rep("risk_model_current_use()", n_drug_ADR_pairs), + min_chance_drug = rep(0.1, n_drug_ADR_pairs), + avg_duration = rep(5, n_drug_ADR_pairs), + max_chance_drug = rep(NULL, n_drug_ADR_pairs), + prob_guaranteed_exposed = rep(1, n_drug_ADR_pairs), + min_chance = rep(0.1, n_drug_ADR_pairs), + max_chance = rep(0.4, n_drug_ADR_pairs), + verbose = FALSE +) +``` + +simulates a cohort, where + +* `n_patients` is the number of patients simulated in the cohort + +* `simulation_time` is the total number of time steps + +* `n_drug_ADR_pairs` is the number of drug-ADR pairs simulated + +* `risk_model` Vector with risk models. Each risk model is given as a string, e.g., `"risk_model_current_use()"`. The vector must have the length `n_drug_ADR_pairs` + +* `min_chance_drug` Vector with the probabilities of the drug being prescribed + when the drug history and the ADR history have no effect. + Must have a length of `n_drug_ADR_pairs`. + +* `avg_duration` Average number of time points a patient is exposed + once exposed to the drug (Determines `max_chance`) + Must have a length of `n_drug_ADR_pairs`. + +* `max_chance_drug` The probability of the ADR when + the drug history and the ADR history have the highest + possible effect (Default: `NULL`) + Must have a length of `n_drug_ADR_pairs`. + +* `guaranteed_exposed` If `TRUE`, the patient is exposed to the drug + at least once + Must have a length of `n_drug_ADR_pairs`. + +* `min_chance` The probability of the ADR when + the drug history has no effect + Must have a length of `n_drug_ADR_pairs`. + +* `max_chance` The probability of the ADR when + the drug history has the highest possible effect + Must have a length of `n_drug_ADR_pairs`. + +### Exposure Model Fit + +One can fit the eight exposure models by running `fit_all_models.R`. For more +information, see the comments to `fit_model`. + +## Acknowledgements + +We gratefully acknowledge the financial support from the innovation fund (“Innovationsfonds”) of the Federal Joint Committee in Germany (grant number: 01VSF16020). + +## Contact + +Louis Dijkstra\ +Leibniz Institute for Prevention Research & Epidemiology +E-mail: dijkstra (at) leibniz-bips.de diff --git a/README.md b/README.md index f6fd129..d966ac8 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,44 @@ -# `expard`: Simulating and Fitting Exposure Models ------------------------------------------------ -`expard` constitutes an `R` package encompassing two primary functionalities: + -1. It serves as a simulator for electronic healthcare data, enabling the simulation of extensive patient populations observed across multiple time points. Leveraging `R`'s functional programming features, the package facilitates the straightforward specification of intricate relationships between drug exposures and adverse drug reactions (ADRs). These relationships may be contingent on various patient attributes such as sex, age, region, among others. +# expard -2. The package includes a methodology designed to fit eight exposure models outlined in the associated paper to electronic healthcare data. + + +[![R-CMD-check](https://github.com/bips-hb/expard/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/bips-hb/expard/actions/workflows/R-CMD-check.yaml) + + +`expard` constitutes an `R` package encompassing two primary +functionalities: + +1. It serves as a simulator for electronic healthcare data, enabling + the simulation of extensive patient populations observed across + multiple time points. Leveraging `R`’s functional programming + features, the package facilitates the straightforward specification + of intricate relationships between drug exposures and adverse drug + reactions (ADRs). These relationships may be contingent on various + patient attributes such as sex, age, region, among others. + +2. The package includes a methodology designed to fit eight exposure + models outlined in the associated paper to electronic healthcare + data. ## Usage ### Simulator -The main function of the package is `generate_cohort` (see `?generate_cohort`). For example, +The main function of the package is `generate_cohort` (see +`?generate_cohort`). For example, + +``` r +library(expard) + +n_drug_ADR_pairs <- 50 -```R generate_cohort( n_patients = 100, simulation_time = 100, - n_drug_ADR_pairs = 50, + n_drug_ADR_pairs = n_drug_ADR_pairs, risk_model = rep("risk_model_current_use()", n_drug_ADR_pairs), min_chance_drug = rep(0.1, n_drug_ADR_pairs), avg_duration = rep(5, n_drug_ADR_pairs), @@ -27,53 +48,59 @@ generate_cohort( max_chance = rep(0.4, n_drug_ADR_pairs), verbose = FALSE ) -``` -simulates a cohort, where +#> Cohort +#> +#> No. patients: 100 +#> No. drug-ADR-pairs: 50 +#> No. time points: 100 +``` + +simulates a cohort, where -* `n_patients` is the number of patients simulated in the cohort +- `n_patients` is the number of patients simulated in the cohort -* `simulation_time` is the total number of time steps +- `simulation_time` is the total number of time steps -* `n_drug_ADR_pairs` is the number of drug-ADR pairs simulated +- `n_drug_ADR_pairs` is the number of drug-ADR pairs simulated -* `risk_model` Vector with risk models. Each risk model is given as a string, e.g., `"risk_model_current_use()"`. The vector must have the length `n_drug_ADR_pairs` +- `risk_model` Vector with risk models. Each risk model is given as a + string, e.g., `"risk_model_current_use()"`. The vector must have the + length `n_drug_ADR_pairs` -* `min_chance_drug` Vector with the probabilities of the drug being prescribed - when the drug history and the ADR history have no effect. - Must have a length of `n_drug_ADR_pairs`. +- `min_chance_drug` Vector with the probabilities of the drug being + prescribed when the drug history and the ADR history have no effect. + Must have a length of `n_drug_ADR_pairs`. -* `avg_duration` Average number of time points a patient is exposed - once exposed to the drug (Determines `max_chance`) - Must have a length of `n_drug_ADR_pairs`. +- `avg_duration` Average number of time points a patient is exposed once + exposed to the drug (Determines `max_chance`) Must have a length of + `n_drug_ADR_pairs`. -* `max_chance_drug` The probability of the ADR when - the drug history and the ADR history have the highest - possible effect (Default: `NULL`) - Must have a length of `n_drug_ADR_pairs`. +- `max_chance_drug` The probability of the ADR when the drug history and + the ADR history have the highest possible effect (Default: `NULL`) + Must have a length of `n_drug_ADR_pairs`. -* `guaranteed_exposed` If `TRUE`, the patient is exposed to the drug - at least once - Must have a length of `n_drug_ADR_pairs`. +- `guaranteed_exposed` If `TRUE`, the patient is exposed to the drug at + least once Must have a length of `n_drug_ADR_pairs`. -* `min_chance` The probability of the ADR when - the drug history has no effect - Must have a length of `n_drug_ADR_pairs`. +- `min_chance` The probability of the ADR when the drug history has no + effect Must have a length of `n_drug_ADR_pairs`. -* `max_chance` The probability of the ADR when - the drug history has the highest possible effect - Must have a length of `n_drug_ADR_pairs`. +- `max_chance` The probability of the ADR when the drug history has the + highest possible effect Must have a length of `n_drug_ADR_pairs`. ### Exposure Model Fit -One can fit the eight exposure models by running `fit_all_models.R`. For more -information, see the comments to `fit_model`. +One can fit the eight exposure models by running `fit_all_models.R`. For +more information, see the comments to `fit_model`. ## Acknowledgements -We gratefully acknowledge the financial support from the innovation fund (“Innovationsfonds”) of the Federal Joint Committee in Germany (grant number: 01VSF16020). +We gratefully acknowledge the financial support from the innovation fund +(“Innovationsfonds”) of the Federal Joint Committee in Germany (grant +number: 01VSF16020). ## Contact -Louis Dijkstra\ +Louis Dijkstra Leibniz Institute for Prevention Research & Epidemiology -E-mail: dijkstra (at) leibniz-bips.de \ No newline at end of file +E-mail: dijkstra (at) leibniz-bips.de diff --git a/data-frame-structures.R b/attic/data-frame-structures.R similarity index 100% rename from data-frame-structures.R rename to attic/data-frame-structures.R diff --git a/figures/.gitignore b/figures/.gitignore deleted file mode 100644 index d6b7ef3..0000000 --- a/figures/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore diff --git a/man/create2x2table.Rd b/man/create2x2table.Rd index 537822e..8094952 100644 --- a/man/create2x2table.Rd +++ b/man/create2x2table.Rd @@ -84,10 +84,10 @@ non-drug eras. \examples{ set.seed(1) -cohort <- generate_cohort(n_patients = 200) +cohort <- generate_cohort(n_patients = 200) -# create the 2x2 contingency table per time-point, -# drug-era and patient: +# create the 2x2 contingency table per time-point, +# drug-era and patient: create2x2table(cohort, method = "time-point") create2x2table(cohort, method = "drug-era") create2x2table(cohort, method = "patient") diff --git a/man/create2x2tables.Rd b/man/create2x2tables.Rd index bd6ba38..8b0b7c0 100644 --- a/man/create2x2tables.Rd +++ b/man/create2x2tables.Rd @@ -17,6 +17,8 @@ create2x2tables( \code{time-point}, \code{drug-era} and \code{patient}. See the description for more information (Default: \code{time-point})} + +\item{verbose}{If \code{TRUE} (default), a progress bar is shown} } \value{ A list of \code{cont_table} objects @@ -88,10 +90,10 @@ non-drug eras. \examples{ set.seed(1) -cohort <- generate_cohort(n_patients = 200) +cohort <- generate_cohort(n_patients = 200) -# create the 2x2 contingency table per time-point, -# drug-era and patient: +# create the 2x2 contingency table per time-point, +# drug-era and patient: create2x2table(cohort, method = "time-point") create2x2table(cohort, method = "drug-era") create2x2table(cohort, method = "patient") diff --git a/man/determine_first_prescription.Rd b/man/determine_first_prescription.Rd index ca8089d..88b0d0f 100644 --- a/man/determine_first_prescription.Rd +++ b/man/determine_first_prescription.Rd @@ -32,5 +32,5 @@ the drug being prescribed does not depend on any previous prescriptions. \examples{ set.seed(1) determine_first_prescription(n_patients = 4, simulation_time = 10, min_chance_drug = 0.1) -# -> [1] 2 3 5 9 +# -> [1] 2 3 5 9 } diff --git a/man/expard-package.Rd b/man/expard-package.Rd new file mode 100644 index 0000000..866803b --- /dev/null +++ b/man/expard-package.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/expard-package.R +\docType{package} +\name{expard-package} +\alias{expard} +\alias{expard-package} +\title{expard: Drug 'EXPosures' and 'ADRs'} +\description{ +An R package for fitting complex drug exposure and adverse drug reaction ('ADR') relationships. It can additionally be used to simulate electronic healthcare record ('EHR') data of patients observed across multiple timepoints. +} +\seealso{ +Useful links: +\itemize{ + \item \url{https://github.com/bips-hb/expard} + \item Report bugs at \url{https://github.com/bips-hb/expard/issues} +} + +} +\author{ +\strong{Maintainer}: Louis Dijkstra \email{louisdijkstra@gmail.com} + +} +\keyword{internal} diff --git a/man/expard.Rd b/man/expard.Rd deleted file mode 100644 index 6430fcd..0000000 --- a/man/expard.Rd +++ /dev/null @@ -1,10 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/zzz.R -\docType{package} -\name{expard} -\alias{expard} -\title{\code{expard}: A package for simulating electronic -health care data and fitting models} -\author{ -Louis Dijkstra -} diff --git a/man/fit_model.Rd b/man/fit_model.Rd index 642d4f8..163b79e 100644 --- a/man/fit_model.Rd +++ b/man/fit_model.Rd @@ -1,12 +1,13 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/fit-model.R -\name{fit_model} +% Please edit documentation in R/fit-all-models.R, R/fit-model.R +\name{fit_all_models} +\alias{fit_all_models} \alias{fit_model} \title{Fit a Model to Cohort Data} \usage{ -fit_model( - pair, - model = c("no-association", "current-use", "past-use", "withdrawal", "delayed", +fit_all_models( + cohort, + models = c("no-association", "current-use", "past-use", "withdrawal", "delayed", "decaying", "delayed+decaying", "long-term"), zero_patients = 0, zero_timepoints = 0, @@ -15,15 +16,32 @@ fit_model( parameters = list(), mc.cores = 1 ) + +fit_model( + cohort, + model = c("no-association", "current-use", "past-use", "withdrawal", "delayed", + "decaying", "delayed+decaying", "long-term"), + zero_patients = 0, + zero_timepoints = 0, + method = c("L-BFGS-B", "Nelder-Mead", "BFGS", "CG", "SANN", "Brent"), + maxiter = 1000, + parameters = list() +) } \arguments{ -\item{model}{Label for a risk model. Can be either ...} +\item{cohort}{A cohort dataset. See details below.} + +\item{zero_patients, zero_timepoints}{Integer values (TODO)} \item{method}{Methods used by the base \code{\link{optim}}-solver} \item{maxiter}{Maximum number iterations for the \code{\link{optim}}-solver} -\item{cohort}{A cohort dataset. See details below.} +\item{parameters}{list (TODO)} + +\item{mc.cores}{Number of cores used for parallelization} + +\item{model}{Label for a risk model. Can be either ...} \item{start}{Starting point for the base \code{\link{optim}}-solver (Default: \code{c(-1,1)})} @@ -74,20 +92,22 @@ for more details on the \code{cohort} object. } \examples{ -cohort <- expard::generate_cohort(n_patients = 1000, - simulation_time = 100, - risk_model = expard::risk_model_immediate(), - verbose = TRUE, - min_chance_drug = probability_model_constant(.3), - max_chance_drug = probability_model_constant(.7), - min_chance_adr = probability_model_constant(.3), - max_chance_adr = probability_model_constant(.6)) +cohort <- generate_cohort( + n_patients = 1000, + simulation_time = 100, + risk_model = expard::risk_model_withdrawal(rate = 3), + verbose = TRUE, + min_chance_drug = probability_model_constant(.3), + max_chance_drug = probability_model_constant(.7), + min_chance_adr = probability_model_constant(.3), + max_chance_adr = probability_model_constant(.6) +) # fit the no effect model -fit_model(cohort, risk_model = expard::risk_model_no_effect()) +fit_model(cohort, risk_model = expard::risk_model_no_effect()) # fit the true immediate effect model -fit_model(cohort, risk_model = expard::risk_model_immediate()) -# note that the estimators are close to the truth (.3 and .6) +fit_model(cohort, risk_model = expard::risk_model_withdrawal(rate = 3)) +# note that the estimators are close to the truth (.3 and .6) } \seealso{ \code{\link{check_cohort}},\code{\link{generate_cohort}} diff --git a/man/generate_adr_history.Rd b/man/generate_adr_history.Rd index 92dc290..52b1db9 100644 --- a/man/generate_adr_history.Rd +++ b/man/generate_adr_history.Rd @@ -4,7 +4,7 @@ \alias{generate_adr_history} \title{Returns ADR History} \usage{ -generate_adr_history(drug_history, risk_model, min_chance, max_chance, ...) +generate_adr_history(drug_history, risk_model, min_chance, max_chance) } \arguments{ \item{drug_history}{Binary vector denoting the diff --git a/man/generate_cohort.Rd b/man/generate_cohort.Rd index f28416e..26bd23b 100644 --- a/man/generate_cohort.Rd +++ b/man/generate_cohort.Rd @@ -42,6 +42,8 @@ the drug history and the ADR history have the highest possible effect (Default: \code{NULL}) Must have a length of \code{n_drug_ADR_pairs}.} +\item{prob_guaranteed_exposed}{Probability of guaranteed exposure} + \item{min_chance}{The probability of the ADR when the drug history has no effect Must have a length of \code{n_drug_ADR_pairs}.} diff --git a/man/generate_drug_history.Rd b/man/generate_drug_history.Rd index 5d0e0c6..0b63e98 100644 --- a/man/generate_drug_history.Rd +++ b/man/generate_drug_history.Rd @@ -28,6 +28,8 @@ possible effect (Default: \code{NULL})} \item{guaranteed_exposed}{If \code{TRUE}, the patient is exposed to the drug at least once} + +\item{...}{Unused} } \value{ \code{1} or \code{0} @@ -39,9 +41,11 @@ The probability depends on the drug prescriptions, the ADR history and the \code{drug_model}. } \examples{ -generate_drug_history(simulation_time = 10, - min_chance = .1, - avg_duration = 5 - guaranteed_exposed = TRUE) +generate_drug_history( + simulation_time = 10, + min_chance = .1, + avg_duration = 5, + guaranteed_exposed = TRUE +) } \concept{Update functions} diff --git a/man/hello.Rd b/man/hello.Rd deleted file mode 100644 index 0fa7c4b..0000000 --- a/man/hello.Rd +++ /dev/null @@ -1,12 +0,0 @@ -\name{hello} -\alias{hello} -\title{Hello, World!} -\usage{ -hello() -} -\description{ -Prints 'Hello, world!'. -} -\examples{ -hello() -} diff --git a/man/loglikelihood.Rd b/man/loglikelihood.Rd index 3111f2e..f2895a4 100644 --- a/man/loglikelihood.Rd +++ b/man/loglikelihood.Rd @@ -2,9 +2,27 @@ % Please edit documentation in R/loglikelihood.R \name{loglikelihood} \alias{loglikelihood} +\alias{loglikelihood_past} +\alias{loglikelihood_withdrawal} +\alias{loglikelihood_delayed} +\alias{loglikelihood_decaying} +\alias{loglikelihood_delayed_decaying} +\alias{loglikelihood_long_term} \title{Negative of the Log-Likelihood Function} \usage{ loglikelihood(betas, risks, adr_history) + +loglikelihood_past(param, past, drug_history, adr_history) + +loglikelihood_withdrawal(param, freq_table) + +loglikelihood_delayed(param, freq_table) + +loglikelihood_decaying(param, freq_table) + +loglikelihood_delayed_decaying(param, freq_table) + +loglikelihood_long_term(param, freq_table) } \arguments{ \item{betas}{Vector with two entries: \code{beta0, beta}} @@ -12,6 +30,16 @@ loglikelihood(betas, risks, adr_history) \item{risks}{Risks determined by the risk model. The risk model was applied to the observed drug prescription history} + +\item{adr_history}{Binary vector with the observed ADR history} + +\item{param}{Vector with parameters.} + +\item{past}{Passed to \code{\link[=risk_model_past]{risk_model_past()}}} + +\item{drug_history}{Binary vector with the observed drug history} + +\item{freq_table}{A data frame with the column \code{unique_value}.} } \description{ \code{loglikelihood} returns the negative diff --git a/man/plot_fit.Rd b/man/plot_fit.Rd index fe832d1..e5bc59b 100644 --- a/man/plot_fit.Rd +++ b/man/plot_fit.Rd @@ -15,15 +15,19 @@ plot_fit( \arguments{ \item{fit}{The fit} +\item{x_label}{The x-label for the plot} + +\item{title}{The plot title} + +\item{y_range}{Used as minimum for the y axis. Guessed if not provided.} + \item{past_values}{If not \code{NULL}, a select number of values for past are used for the plot} - -\item{xlab}{The x-label} } \value{ ggplot } \description{ Plots the BIC for the different risk models that were fitted by the -function \code{\link{fit_all_models}}. +function \code{\link[=fit_all_models]{fit_all_models()}}. } diff --git a/man/plot_risk.Rd b/man/plot_risk.Rd index 4f075b7..d87d5ff 100644 --- a/man/plot_risk.Rd +++ b/man/plot_risk.Rd @@ -6,7 +6,7 @@ \usage{ plot_risk( drug_history = c(rep(0, 4), rep(1, 6), rep(0, 10)), - risk_model = risk_model_immediate(), + risk_model = risk_model_decaying(3), simulation_time = NULL, title = "", ylim = c(0, 1), @@ -18,12 +18,12 @@ plot_risk( \arguments{ \item{drug_history}{Binary vector denoting the drug prescription history. -(Default: \code{0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0})} +(Default: \verb{0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0})} \item{risk_model}{One of the risk models} \item{simulation_time}{If not \code{NULL}, total number of time points, i.e., -\code{0 0 0 0 1 1 1 1 1 1 0 0 0 0 ...}. (Default: \code{NULL})} +\verb{0 0 0 0 1 1 1 1 1 1 0 0 0 0 ...}. (Default: \code{NULL})} \item{title}{Title of the plot} @@ -40,23 +40,24 @@ vertical dashed red lines (Default: \code{TRUE})} \item{alpha}{Alpha value for shaded area (Default: \code{.3})} } \value{ -A \code{ggplot2} plot +A \link{ggplot2} plot } \description{ Plots the risk function's behavior for a given drug prescription history. The \eqn{x}-axis denote the -drug prescriptions and the \eqn{y}-axis represent the +drug prescriptions and the \code{y}-axis represent the risk level, i.e., \code{1} is maximal risk, \code{0} minimal risk. } \examples{ drug_history <- c(rep(0, 4), rep(1, 6), rep(0, 10)) -risk_model <- risk_model_immediate() +risk_model <- risk_model_withdrawal(rate = 3) # create the plot -p <- plot_risk(drug_history, - risk_model, - title = "Direct effect model") +p <- plot_risk(drug_history, + risk_model, + title = "Direct effect model" +) p } diff --git a/man/print.cohort.Rd b/man/print.cohort.Rd index a8314de..c384cf2 100644 --- a/man/print.cohort.Rd +++ b/man/print.cohort.Rd @@ -4,7 +4,12 @@ \alias{print.cohort} \title{Print function for \code{\link{generate_cohort}}} \usage{ -\method{print}{cohort}(cohort) +\method{print}{cohort}(x, ...) +} +\arguments{ +\item{x}{A \code{cohort} object.} + +\item{...}{Unused.} } \description{ Print function for \code{\link{generate_cohort}} diff --git a/man/print.cont_table.Rd b/man/print.cont_table.Rd index 1d97083..ac343a6 100644 --- a/man/print.cont_table.Rd +++ b/man/print.cont_table.Rd @@ -4,7 +4,12 @@ \alias{print.cont_table} \title{Print function for 2x2 tables} \usage{ -\method{print}{cont_table}(table) +\method{print}{cont_table}(x, ...) +} +\arguments{ +\item{x}{A \code{cont_table} object.} + +\item{...}{Unused.} } \description{ Print function for 2x2 tables diff --git a/man/print.drug_ADR_pair.Rd b/man/print.drug_ADR_pair.Rd index 1b49c63..9f9a5ce 100644 --- a/man/print.drug_ADR_pair.Rd +++ b/man/print.drug_ADR_pair.Rd @@ -4,7 +4,12 @@ \alias{print.drug_ADR_pair} \title{Function for printing a drug-ADR pair} \usage{ -\method{print}{drug_ADR_pair}(drug_ADR_pair) +\method{print}{drug_ADR_pair}(x, ...) +} +\arguments{ +\item{x}{A \code{drug_ADR_pair} object.} + +\item{...}{Unused.} } \description{ Function for printing a drug-ADR pair diff --git a/man/print.expardfit2.Rd b/man/print.expardfit2.Rd index 10664f2..810f88d 100644 --- a/man/print.expardfit2.Rd +++ b/man/print.expardfit2.Rd @@ -4,7 +4,12 @@ \alias{print.expardfit2} \title{Print function for the hccd fit_model} \usage{ -\method{print}{expardfit2}(fit) +\method{print}{expardfit2}(x, ...) +} +\arguments{ +\item{x}{A \code{expardfit2} object.} + +\item{...}{Unused.} } \description{ Print function for the hccd fit_model diff --git a/man/print.patient.Rd b/man/print.patient.Rd index 65d10c3..d7bcf10 100644 --- a/man/print.patient.Rd +++ b/man/print.patient.Rd @@ -4,7 +4,12 @@ \alias{print.patient} \title{Function for printing a patient} \usage{ -\method{print}{patient}(patient) +\method{print}{patient}(x, ...) +} +\arguments{ +\item{x}{A \code{patient} object.} + +\item{...}{Unused.} } \description{ Function for printing a patient diff --git a/man/risk_model_current_use.Rd b/man/risk_model_current_use.Rd deleted file mode 100644 index 798926c..0000000 --- a/man/risk_model_current_use.Rd +++ /dev/null @@ -1,37 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_current_use} -\alias{risk_model_current_use} -\title{Risk Model 'Immediate'} -\usage{ -risk_model_current_use() -} -\value{ -A risk model -} -\description{ -A risk model reflects how the probability of -suffering the ADR changes with the drug exposures -of a patient. It returns \code{0} when the drug -prescription history has no effect, and \code{1} -when the patient is at maximal risk. -In this case, the probability of the ADR -is maximal only when the patient is currently -exposed. -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) -risk_model <- risk_model_immediate() -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_past}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_decaying.Rd b/man/risk_model_decaying.Rd deleted file mode 100644 index 17d9dd2..0000000 --- a/man/risk_model_decaying.Rd +++ /dev/null @@ -1,34 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_decaying} -\alias{risk_model_decaying} -\title{Risk Model 'Decaying'} -\usage{ -risk_model_decaying(rate) -} -\arguments{ -\item{rate}{The rate with which the risk dissipates} -} -\value{ -A risk model -} -\description{ -Risk Model 'Decaying' -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) - -risk_model <- risk_model_withdrawal(rate = 1.2) -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_past}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_delayed.Rd b/man/risk_model_delayed.Rd deleted file mode 100644 index 563059e..0000000 --- a/man/risk_model_delayed.Rd +++ /dev/null @@ -1,34 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_delayed} -\alias{risk_model_delayed} -\title{Risk Model 'Delayed'} -\usage{ -risk_model_delayed(mu, sigma) -} -\arguments{ -\item{rate}{The rate with which the risk dissipates} -} -\value{ -A risk model -} -\description{ -Risk Model 'Delayed' -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) - -risk_model <- risk_model_withdrawal(rate = 1.2) -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_past}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_duration.Rd b/man/risk_model_duration.Rd deleted file mode 100644 index 51488ec..0000000 --- a/man/risk_model_duration.Rd +++ /dev/null @@ -1,46 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_duration} -\alias{risk_model_duration} -\title{Risk Model 'Withdrawal'} -\usage{ -risk_model_duration(duration) -} -\arguments{ -\item{rate}{The rate with which the risk dissipates} -} -\value{ -A risk model -} -\description{ -A risk model reflects how the probability of -suffering the ADR changes with the drug exposures -of a patient. It returns \code{0} when the drug -prescription history has no effect, and \code{1} -when the patient is at maximal risk. -In this case, once the patient is no longer exposed -to the drug, the probability of the ADR peaks -and then dissipates exponentially. -Let \eqn{\tau} be the number of time points since -the patient was prescribed the drug last. The return -value is the given by -\deqn{\exp(-\gamma \cdot (\tau - 1))} -where \eqn{\gamma} is \code{rate}. -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) - -risk_model <- risk_model_withdrawal(rate = 1.2) -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_past}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_long_term.Rd b/man/risk_model_long_term.Rd deleted file mode 100644 index de780ab..0000000 --- a/man/risk_model_long_term.Rd +++ /dev/null @@ -1,51 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_long_term} -\alias{risk_model_long_term} -\title{Risk Model 'Long Time After'} -\usage{ -risk_model_long_term(rate, delay) -} -\arguments{ -\item{rate}{The rate with which the risk increases} - -\item{delay}{How long it takes before the risk is .5} -} -\value{ -A risk model -} -\description{ -A risk model reflects how the probability of -suffering the ADR changes with the drug exposures -of a patient. It returns \code{0} when the drug -prescription history has no effect, and \code{1} -when the patient is at maximal risk. -In this case, the risk of the ADR increases -only after a certain moment in time before it -reaches the maximal risk. -Let \eqn{t_0} be the time point that the drug -was prescribed for the first time, and \eqn{\delta} -be the number of time points since first description -that the function returns 0.5 ("half way"). The -return value is -\deqn{1 / (1 + \exp(-\gamma \cdot (t_0 - \delta)))} -where \eqn{\gamma} is \code{rate}. Note that this -is a sigmoid function. -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1) - -risk_model <- risk_model_long_time_after(rate = .5, delay = 9) -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_past}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_no_association.Rd b/man/risk_model_no_association.Rd deleted file mode 100644 index f9a44d5..0000000 --- a/man/risk_model_no_association.Rd +++ /dev/null @@ -1,37 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_no_association} -\alias{risk_model_no_association} -\title{Risk Model 'No Association'} -\usage{ -risk_model_no_association() -} -\value{ -A risk model -} -\description{ -A risk model reflects how the probability of -suffering the ADR changes with the drug exposures -of a patient. It returns \code{0} when the drug -prescription history has no effect, and \code{1} -when the patient is at maximal risk. -In this case, the drug has no effect on the ADR -what so ever. -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) -risk_model <- risk_model_no_effect() -risk_model() -# -> 0 -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_past}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_past.Rd b/man/risk_model_past.Rd deleted file mode 100644 index a215573..0000000 --- a/man/risk_model_past.Rd +++ /dev/null @@ -1,46 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_past} -\alias{risk_model_past} -\title{Risk Model 'Withdrawal'} -\usage{ -risk_model_past(past) -} -\arguments{ -\item{rate}{The rate with which the risk dissipates} -} -\value{ -A risk model -} -\description{ -A risk model reflects how the probability of -suffering the ADR changes with the drug exposures -of a patient. It returns \code{0} when the drug -prescription history has no effect, and \code{1} -when the patient is at maximal risk. -In this case, once the patient is no longer exposed -to the drug, the probability of the ADR peaks -and then dissipates exponentially. -Let \eqn{\tau} be the number of time points since -the patient was prescribed the drug last. The return -value is the given by -\deqn{\exp(-\gamma \cdot (\tau - 1))} -where \eqn{\gamma} is \code{rate}. -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) - -risk_model <- risk_model_withdrawal(rate = 1.2) -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_withdrawal}()} -} -\concept{Risk models} diff --git a/man/risk_model_withdrawal.Rd b/man/risk_model_withdrawal.Rd deleted file mode 100644 index ce118f0..0000000 --- a/man/risk_model_withdrawal.Rd +++ /dev/null @@ -1,46 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/risk-models.R -\name{risk_model_withdrawal} -\alias{risk_model_withdrawal} -\title{Risk Model 'Withdrawal'} -\usage{ -risk_model_withdrawal(rate) -} -\arguments{ -\item{rate}{The rate with which the risk dissipates} -} -\value{ -A risk model -} -\description{ -A risk model reflects how the probability of -suffering the ADR changes with the drug exposures -of a patient. It returns \code{0} when the drug -prescription history has no effect, and \code{1} -when the patient is at maximal risk. -In this case, once the patient is no longer exposed -to the drug, the probability of the ADR peaks -and then dissipates exponentially. -Let \eqn{\tau} be the number of time points since -the patient was prescribed the drug last. The return -value is the given by -\deqn{\exp(-\gamma \cdot (\tau - 1))} -where \eqn{\gamma} is \code{rate}. -} -\examples{ -drug_history <- c(1, 0, 1, 0, 0) - -risk_model <- risk_model_withdrawal(rate = 1.2) -risk_model(drug_history) -} -\seealso{ -Other Risk models: -\code{\link{risk_model_current_use}()}, -\code{\link{risk_model_decaying}()}, -\code{\link{risk_model_delayed}()}, -\code{\link{risk_model_duration}()}, -\code{\link{risk_model_long_term}()}, -\code{\link{risk_model_no_association}()}, -\code{\link{risk_model_past}()} -} -\concept{Risk models} diff --git a/man/risk_models.Rd b/man/risk_models.Rd new file mode 100644 index 0000000..dd70618 --- /dev/null +++ b/man/risk_models.Rd @@ -0,0 +1,157 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/risk-models.R +\name{risk_model_no_association} +\alias{risk_model_no_association} +\alias{risk_model_current_use} +\alias{risk_model_past} +\alias{risk_model_duration} +\alias{risk_model_withdrawal} +\alias{risk_model_delayed} +\alias{risk_model_decaying} +\alias{risk_model_delayed_decaying} +\alias{risk_model_long_term} +\title{Risk Model 'No Association'} +\usage{ +risk_model_no_association() + +risk_model_current_use() + +risk_model_past(past) + +risk_model_duration(duration) + +risk_model_withdrawal(rate) + +risk_model_delayed(mu, sigma) + +risk_model_decaying(rate) + +risk_model_delayed_decaying(mu, sigma, rate) + +risk_model_long_term(rate, delay) +} +\arguments{ +\item{past}{Reference time point > 0.} + +\item{duration}{The duration to check against.} + +\item{rate}{The rate with which the risk increases} + +\item{mu, sigma}{The parameters to \code{\link[=dnorm]{dnorm()}} used to model the risk.} + +\item{delay}{How long it takes before the risk is .5} +} +\value{ +A risk model +} +\description{ +A risk model reflects how the probability of +suffering the ADR changes with the drug exposures +of a patient. It returns \code{0} when the drug +prescription history has no effect, and \code{1} +when the patient is at maximal risk. +In this case, the drug has no effect on the ADR +what so ever. + +A risk model reflects how the probability of +suffering the ADR changes with the drug exposures +of a patient. It returns \code{0} when the drug +prescription history has no effect, and \code{1} +when the patient is at maximal risk. +In this case, the probability of the ADR +is maximal only when the patient is currently +exposed. + +A risk model reflects how the probability of +suffering the ADR changes with the drug exposures +of a patient. It returns \code{0} when the drug +prescription history has no effect, and \code{1} +when the patient is at maximal risk. +In this case, once the patient is no longer exposed +to the drug, the probability of the ADR peaks +and then dissipates exponentially. +Let \eqn{\tau} be the number of time points since +the patient was prescribed the drug last. The return +value is the given by +\deqn{\exp(-\gamma \cdot (\tau - 1))} +where \eqn{\gamma} is \code{rate}. + +A risk model reflects how the probability of +suffering the ADR changes with the drug exposures +of a patient. It returns \code{0} when the drug +prescription history has no effect, and \code{1} +when the patient is at maximal risk. +In this case, once the patient is no longer exposed +to the drug, the probability of the ADR peaks +and then dissipates exponentially. +Let \eqn{\tau} be the number of time points since +the patient was prescribed the drug last. The return +value is the given by +\deqn{\exp(-\gamma \cdot (\tau - 1))} +where \eqn{\gamma} is \code{rate}. + +A risk model reflects how the probability of +suffering the ADR changes with the drug exposures +of a patient. It returns \code{0} when the drug +prescription history has no effect, and \code{1} +when the patient is at maximal risk. +In this case, once the patient is no longer exposed +to the drug, the probability of the ADR peaks +and then dissipates exponentially. +Let \eqn{\tau} be the number of time points since +the patient was prescribed the drug last. The return +value is the given by +\deqn{\exp(-\gamma \cdot (\tau - 1))} +where \eqn{\gamma} is \code{rate}. + +A risk model reflects how the probability of +suffering the ADR changes with the drug exposures +of a patient. It returns \code{0} when the drug +prescription history has no effect, and \code{1} +when the patient is at maximal risk. +In this case, the risk of the ADR increases +only after a certain moment in time before it +reaches the maximal risk. +Let \eqn{t_0} be the time point that the drug +was prescribed for the first time, and \eqn{\delta} +be the number of time points since first description +that the function returns 0.5 ("half way"). The +return value is +\deqn{1 / (1 + \exp(-\gamma \cdot (t_0 - \delta)))} +where \eqn{\gamma} is \code{rate}. Note that this +is a sigmoid function. +} +\examples{ +drug_history <- c(1, 0, 1, 0, 0) +risk_model <- risk_model_no_effect() +risk_model() +# -> 0 +drug_history <- c(1, 0, 1, 0, 0) +risk_model <- risk_model_withdrawal(rate = 3) +risk_model(drug_history) +drug_history <- c(1, 0, 1, 0, 0) + +risk_model <- risk_model_past(past = 2) +risk_model(drug_history) +drug_history <- c(1, 0, 1, 0, 0) + +risk_model <- risk_model_withdrawal(rate = 1.2) +risk_model(drug_history) +drug_history <- c(1, 0, 1, 0, 0) + +risk_model <- risk_model_withdrawal(rate = 1.2) +risk_model(drug_history) +drug_history <- c(1, 0, 1, 0, 0) + +risk_model <- risk_model_delayed(5, 1) +risk_model(drug_history) +drug_history <- c(1, 0, 1, 0, 0) + +risk_model <- risk_model_decaying(rate = 1.2) +risk_model(drug_history) +drug_history <- c(1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1) + +risk_model <- risk_model_long_time_after(rate = .5, delay = 9) +risk_model(drug_history) +} +\concept{Risk models}