diff --git "a/data/dataset_Toxicology.csv" "b/data/dataset_Toxicology.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Toxicology.csv" @@ -0,0 +1,5871 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Toxicology","ToxPi/toxpiR","CONTRIBUTING.md",".md","3635","38","# Contributing Guide + +Filing issues +------------- + +Please read these points carefully and follow them while filing issues. + +- **One issue for one purpose**. Don't add more than one *bug*, *feature request*, or *documentation request* on to the same issue. Take the time to read through the current issues to ensure your issue is not already listed. +- If you've found a *bug*, thank you for reporting! Please include a reproducible example of your bug in the issue. +- If you need *support* or have a general *question*, please consider asking the question on [StackOverflow](http://www.stackoverflow.com) +- For the project contributors, please label new issues using the following rules: + - *bugs* should be labeled ""bug"" + - *feature requests* or *suggestions* should be labeled ""enhancement"" + - *questions* or *requests for support* should be labeled ""question"" + +Pull Requests +------------- + +Please file an issue before creating PRs so that it can be discussed first *before* you invest time implementing it. + +1. Please create all pull requests (PR) against the `dev` branch. +2. Create **one PR per feature/bug fix**. Each PR should be associated with an Issue. +3. Create a branch for that feature/bug fix, named 'issue-N' where N is the Issue number, and use that as a base for your pull requests. Pull requests directly against your version of `dev/main` will not be accepted. +4. Please squash temporary stage commits together before issuing a PR. +5. All commit messages should have two components: (1) a headerer on the first line beginning with ""issue-N:"" and containing no more than 50 characters, and (2) a body with 1 empty line after the header then at least a sentence or two in the commit body detailing all changes and justifications. Lines in the commit body should be wrapped to no more than 72 characters per line, and can contain multiple paragraphs.[1](#myfootnote1) +5. In your pull request's description, please state clearly as to what your PR does, i.e., what FR or bug your PR addresses, along with the issue number. For e.g, ""Closes #717: tcplLoadData no longer errors with missing data."" +7. Please build and test the package using `R CMD check --as-cran` against your branch source package archive `.tar.gz` file. You may want to add `--no-manual`, `--no-build-vignettes` or `--ignore-vignettes` (R 3.3.0+) options to reduce dependencies required to perform check. PRs that fail `check` cannot be merged. Additionally, check the tests using `devtools::test()` and ensure they pass or the failing tests are updated appropriately +8. The NEWS file also has to be updated while fixing or implementing an issue. It should mention the issue number and what the issue is being closed. Also add a ""Thanks to @your_name for the PR"". + +**References:** If you are not sure how to issue a PR, but would like to contribute, these links should help get you started: + +1. **[How to Github: Fork, Branch, Track, Squash and Pull request](https://gun.io/blog/how-to-github-fork-branch-and-pull-request/)**. +2. **[Squashing Github pull requests into a single commit](http://eli.thegreenplace.net/2014/02/19/squashing-github-pull-requests-into-a-single-commit)**. + +*This guide was modified from the contributing guide for the [data.table](https://github.com/Rdatatable/data.table) repository* + +1: To make it easier to count the characters per line you can edit your $HOME/.vimrc ($HOME/_vimrc on Windows) to include "":set ruler"" which will display the line and position numbers in the bottom right corner of the terminal when editing the commit messages. +","Markdown" +"Toxicology","ToxPi/toxpiR","NEWS.md",".md","919","27","# toxpiR 1.3.1 + +* Removed pryr dependency as it is scheduled for removal from CRAN +* Updated toxpi web links to a github.io address +* Minor updates to github workflow + + +# toxpiR 1.3.0 + +* Added 'txpMissing' slot to TxpResult; this stores information regarding the + amount of missing data in the dataset per slice +* Added ggplot capabilities for plotting with several new aesthetics +* Updated vignettes +* Transferred maintainer to Jonathon F Fleming + + +# toxpiR 1.2.0 + +* Now require R>=4.0 due to reports of installation issues +* Added 'txpValueNames' method for TxpModel +* Added 'txpExportGui' function +* Added 'TxpResultParam' object and 'txpResultParam' slot to TxpResult; this + stores the parameters controlling the calculation of the scores, e.g. the + rank ties method +* Modified the log transformation functions within txpImportGui to match the + negative value handling behavior in the GUI +* Updated vignettes","Markdown" +"Toxicology","ToxPi/toxpiR","LICENSE.md",".md","34904","596","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 +<>. +","Markdown" +"Toxicology","ToxPi/toxpiR","man-roxygen/roxgn-calcTxpModelList.R",".R","567","13","#' @examples +#' ## Calculate scores for list of models; returns TxpResultList object +#' txpCalculateScores(model = TxpModelList(m1 = txp_example_model, +#' m2 = txp_example_model), +#' input = txp_example_input, +#' id.var = ""name"") +#' resLst <- txpCalculateScores(model = list(m1 = txp_example_model, +#' m2 = txp_example_model), +#' input = txp_example_input, +#' id.var = ""name"") +#' + +","R" +"Toxicology","ToxPi/toxpiR","man-roxygen/roxgn-calcTxpModel.R",".R","245","8","#' @examples +#' ## Calculate scores for single model; returns TxpResult object +#' res <- txpCalculateScores(model = txp_example_model, +#' input = txp_example_input, +#' id.var = ""name"") +#' + +","R" +"Toxicology","ToxPi/toxpiR","man-roxygen/roxgn-loadExamples.R",".R","190","7","#' @examples +#' ## Load example dataset & model; see ?TxpModel for building model objects +#' data(txp_example_input, package = ""toxpiR"") +#' data(txp_example_model, package = ""toxpiR"") +#' + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpResult-plot.R",".R","12318","433","##----------------------------------------------------------------------------## +## plot methods for TxpResult +##----------------------------------------------------------------------------## + +#' @name TxpResult-plot +#' @title Plot TxpResult objects +#' @description Plot [TxpResult] objects +#' @aliases plot +#' +#' @param x [TxpResult] object +#' @param y Rank vector, i.e. `txpRanks(x)` +#' @param package Character scalar, choice of ""grid"" or ""ggplot2"" for plotting +#' ToxPi profiles +#' @param fills Vector of colors to fill slices. Set to NULL to use default +#' @param showScore Logical scalar, overall score printed below the name when +#' `TRUE` +#' @param labels Integer vector, indices of `x` to label in the rank plot +#' @param margins Passed to [grid::plotViewport]; only affects the scatterplot +#' region margins +#' @param gp,vp,name Passed to [grid::frameGrob] when creating the plotting +#' area +#' @param newpage Logical scalar, [grid::grid.newpage] called prior to plotting +#' when `TRUE` +#' @param ... Passed to [pieGridGrob] when plotting ToxPi and to pointsGrob +#' when plotting ranks +#' @param ncol Number of columns for ggplot2 ToxPi profiles +#' @param bgColor,borderColor,sliceBorderColor,sliceValueColor,sliceLineColor +#' Various color options when creating ggplot2 ToxPi profiles. Set to NULL +#' for no color +#' @param showMissing Boolean for coloring data missingness in ggplot2 +#' ToxPi profiles +#' @param showCenter Boolean for showing inner circle in ggplot2 ToxPi +#' profiles. When set to False overrides showMissing +#' +#' @details +#' It is strongly recommended to use a specific device (e.g., [grDevices::png], +#' [grDevices::pdf]) when creating rank plots. +#' Using a GUI device will likely lead to inaccurate labeling, and any changes +#' to the device size WILL lead to inaccurate labeling. +#' +#' The plotting is built on the [grid::grid-package], and can be adjusted or +#' edited as such. +#' +#' If the labels are running of the device, the top or bottom margins can be +#' increased with the `margins` parameter. +#' +#' ToxPi profiles can also be plotted using the ggplot2 package. +#' +#' @template roxgn-loadExamples +#' @template roxgn-calcTxpModel +#' +#' @examples +#' library(grid) +#' plot(res) +#' plot(res[order(txpRanks(res))[1:4]]) +#' +#' library(ggplot2) +#' plot(res, package = ""gg"") +#' plot(res[order(txpRanks(res))], package = ""gg"", ncol = 5) + +#' theme(legend.position = ""bottom"") +#' +#' plot(res, txpRanks(res)) +#' plot(res, txpRanks(res), pch = 16, size = unit(0.75, ""char"")) +#' +#' ## Will likely make inaccurate labels within a GUI, e.g. RStudio +#' ## use png, pdf, etc. to get accurate labels +#' \dontrun{ +#' tmpPdf <- tempfile() +#' pdf(tmpPdf) +#' plot(res, txpRanks(res), labels = c(10, 4, 2), pch = 16) +#' dev.off() +#' } +#' +#' @return No return value when using grid; called for side effect (i.e. +#' drawing in current graphics device). Will return ggplot2 object otherwise. + +NULL + +.TxpResult.toxpiPlot <- function( + x, + package = c(""grid"", ""ggplot2""), + fills = NULL, + showScore = TRUE, + gp = NULL, + vp = NULL, + name = NULL, + newpage = TRUE, + ..., + ncol = NULL, + bgColor = ""grey80"", + borderColor = ""white"", + sliceBorderColor = ""white"", + sliceValueColor = NULL, + sliceLineColor = NULL, + showMissing = TRUE, + showCenter = TRUE) { + + if (tolower(substr(package[1], 0, 2)) == ""gg"") { + .TxpResult.toxpiGGPlot( + x, fills, showScore, ncol, bgColor, borderColor, + sliceBorderColor, sliceValueColor, sliceLineColor, showMissing, + showCenter + ) + } else { + .TxpResult.toxpiGridPlot( + x, fills, showScore, gp, vp, name, newpage, ... + ) + } + +} + +#' @describeIn TxpResult-plot Plot ToxPi diagrams +#' @export + +setMethod(""plot"", c(""TxpResult"", ""missing""), .TxpResult.toxpiPlot) + +#' @import grid + +.TxpResult.toxpiGridPlot <- function(x, + fills = NULL, + showScore = TRUE, + gp = NULL, + vp = NULL, + name = NULL, + newpage = TRUE, + ...) { + + if (is.null(fills)) fills <- getOption(""txp.fills"", TXP_FILLS) + sNames <- names(txpSlices(x)) + pg <- pieGridGrob(txpSliceScores(x, adjusted = FALSE), + wts = txpWeights(x), + labels = txpIDs(x), + fills = fills, + showRadSum = showScore, + ...) + lg <- boxLegendGrob(labels = sNames, fills = fills) + wids <- unit(c(10, 1), ""grobwidth"", lg) + fg <- frameGrob(layout = grid.layout(nrow = 1, ncol = 2, widths = wids), + name = name, + gp = gp, + vp = vp) + fg <- placeGrob(frame = fg, grob = pg, row = 1, col = 1) + fg <- placeGrob(frame = fg, grob = lg, row = 1, col = 2) + if (newpage) grid.newpage() + grid.draw(fg) + +} + +#' @importFrom rlang is_named is_integerish is_scalar_logical +#' @import grid + +.TxpResult.rankPlot <- function(x, y, labels = NULL, newpage = TRUE, + margins = c(4, 0, 1, 1), + name = NULL, gp = NULL, vp = NULL, ...) { + + stopifnot(is_scalar_logical(newpage)) + stopifnot(is.null(labels) || is_integerish(labels)) + + drawLabels <- !is.null(labels) + + if (newpage) grid.newpage() + + if (drawLabels) { + stopifnot(is_named(x)) + names(labels) <- txpIDs(x[labels]) + labelWidth <- .maxStrWidth(names(labels)) + unit(5, ""char"") + } else { + labelWidth <- unit(0, ""mm"") + } + + gl <- grid.layout(nrow = 1, ncol = 2, unit.c(labelWidth, unit(1, ""null""))) + + fg <- frameGrob(layout = gl, name = name, gp = gp, vp = vp) + + rnk <- annScatterGrob(x = txpScores(x), + y = y, + ann = if (drawLabels) labels else NULL, + yscale = rev(extendrange(range(y))), + yaxis = FALSE, + xlab = ""ToxPi Score"", + margins = margins, + ...) + + fg <- placeGrob(frame = fg, grob = rnk, row = 1, col = 2) + grid.draw(fg) + + if (drawLabels) { + lblGrob <- .refLabel(names(labels), labelWidth) + fg <- placeGrob(frame = fg, grob = lblGrob, row = 1, col = 1) + grid.draw(fg$children[fg$childrenOrder[2]]) + } + +} + +#' @describeIn TxpResult-plot Plot ToxPi ranks +#' @export + +setMethod(""plot"", c(""TxpResult"", ""numeric""), .TxpResult.rankPlot) + +#' @import ggplot2 + +.TxpResult.toxpiGGPlot <- function( + x, + fills = NULL, + showScore = TRUE, + ncol = NULL, + bgColor = ""grey80"", + borderColor = ""white"", + sliceBorderColor = ""white"", + sliceValueColor = NULL, + sliceLineColor = NULL, + showMissing = TRUE, + showCenter = TRUE + ) { + + # Set to NULL to prevent note from devtools::check() + left <- right <- mid <- radii <- Slices <- NULL + + if (is.null(fills)) { + fills <- getOption(""txp.fills"", TXP_FILLS) + } + + #get plotting df + toxResultDF <- as.data.frame(x) + txpModel <- txpModel(x) + profileDF <- .getPlotList(txpWeights(x), names(txpModel), toxResultDF) + + #make plot + if(showCenter){ + innerRad <- 0.1 # percent + } else { + innerRad <- 0 + } + yText <- 1.22 + + plot <- ggplot2::ggplot(profileDF) + + ggplot2::theme_void() + + ggplot2::ylim(0, ifelse(is.null(sliceValueColor), 1, yText)) + + ggplot2::theme(plot.margin = ggplot2::margin(2, 2, 2, 2, unit = ""mm"")) + + if (showScore) { + plot <- plot + ggplot2::facet_wrap( + ~factor(NameScore, levels = unique(profileDF$NameScore)), + ncol = ncol + ) + } else { + plot <- plot + ggplot2::facet_wrap( + ~factor(Name, levels = unique(profileDF$Name)), + ncol = ncol + ) + } + + if (!is.null(sliceLineColor)) { + nSlices <- length(unique(profileDF$Slices)) + x1 <- profileDF$left + y1 <- rep(innerRad, length(x1)) + xend <- x1 + yend <- rep(1, length(x1)) + plot <- plot + ggplot2::geom_segment( + ggplot2::aes(x = x1, y = y1, xend = xend, yend = yend), + linetype = ""dashed"", + colour = sliceLineColor + ) + } + if(showCenter){ + if (showMissing) { + missingData <- txpMissing(x) + } else { + missingData <- rep(0, length(txpSlices(x))) + } + plot <- plot + ggplot2::geom_rect( + ggplot2::aes(xmin = left, xmax = right, ymin = 0, ymax = innerRad), + fill = rep(grDevices::gray(1 - missingData), length(x)) + ) + } + + if (!is.null(sliceBorderColor)) { + plot <- plot + ggplot2::geom_rect( + ggplot2::aes( + xmin = left, + xmax = right, + ymin = innerRad, + ymax = innerRad + radii * (1 - innerRad), + fill = Slices + ), + color = sliceBorderColor, + linewidth = 0.5 + ) + } else { + plot <- plot + ggplot2::geom_rect( + ggplot2::aes( + xmin = left, + xmax = right, + ymin = innerRad, + ymax = innerRad + radii * (1 - innerRad), + fill = Slices + ) + ) + } + + plot <- plot + ggplot2::scale_fill_manual( + breaks = unique(profileDF$Slices), + values = fills + ) + + if (!is.null(borderColor)) { + plot <- plot + ggplot2::geom_hline( + yintercept = 1, color = borderColor, linewidth = 0.5 + ) + } + + if (!is.null(sliceValueColor)) { + plot <- plot + ggplot2::geom_text( + ggplot2::aes( + x = mid, + y = yText, + label = as.character(radii) + ), + colour = sliceValueColor, + size = 3 + ) + } + + plot <- plot + ggplot2::geom_hline( + yintercept = innerRad, color = ""black"", linewidth = 0.4 + ) + + if (!is.null(bgColor)) { + plot <- plot + ggplot2::theme( + panel.background = ggplot2::element_rect(fill = bgColor, color = bgColor) + ) + } + + plot + ggplot2::coord_polar(start = 3 * pi / 2, direction = -1) + +} + +.getSlicePositions <- function(wts) { + endWts <- cumsum(wts) + startWts <- c(0, utils::head(endWts, -1)) + list(start = startWts, end = endWts) +} + +# Generate dataframe for plotting a profile +.generateProfileDF <- function(startWts, endWts, radii, sliceNames, id, score) { + df <- data.frame( + left = startWts, + right = endWts, + mid = (startWts + endWts) / 2, + radii = round(radii, 3), + Slices = sliceNames, + Name = id, + Score = round(score, 4) + ) + df$NameScore <- paste(df$Name, df$Score, sep = ""\n"") + df +} + +#get dataframe containing all necessary info for selected samples +.getPlotList <- function(wts, sliceNames, data) { + pos <- .getSlicePositions(wts) + do.call(rbind, lapply(1:nrow(data), function(x) { + .generateProfileDF( + pos$start, pos$end, unlist(data[x, sliceNames]), sliceNames, + data[x, ""id""], data[x, ""score""] + ) + })) +} + +.maxStrWidth <- function(x) { + wids <- lapply(x, stringWidth) + wids[[which.max(sapply(wids, convertWidth, ""inches""))]] +} + +.refLabel <- function(lbl, xloc) { + + yloc <- do.call(""unit.c"", sapply(lbl, .getDeviceLoc)[""y"", ]) + ord <- order(yloc) + yloc <- yloc[ord] + lbl <- lbl[ord] + + n <- length(lbl) + ypos <- yloc + wd <- convertUnit(unit(1, ""char""), ""in"") + ht <- wd*1.2 + mid <- (n + 1) %/% 2 + # ypos[mid] <- yloc[mid] + if (n > 1) { + for (i in (mid + 1):n) { + ypos[i] <- max(yloc[i], ypos[i - 1] + ht) + } + } + if (n > 2) { + for (i in (mid - 1):1) { + ypos[i] <- min(yloc[i], ypos[i + 1] - ht) + } + } + + x1 <- rep(xloc, n) + x2 <- x1 - 0.5*wd + x3 <- x2 - 2*wd + x4 <- x3 - 0.5*wd + + s1 <- segmentsGrob(x0 = unit(x1, ""npc""), + y0 = unit(yloc, ""npc""), + x1 = unit(x2, ""npc""), + y1 = unit(yloc, ""npc"")) + s2 <- segmentsGrob(x0 = unit(x2, ""npc""), + y0 = unit(yloc, ""npc""), + x1 = unit(x3, ""npc""), + y1 = unit(ypos, ""npc"")) + s3 <- segmentsGrob(x0 = unit(x3, ""npc""), + y0 = unit(ypos, ""npc""), + x1 = unit(x4, ""npc""), + y1 = unit(ypos, ""npc"")) + tg <- textGrob(label = lbl, x = wd, y = ypos, just = ""left"") + + gTree(children = gList(s1, s2, s3, tg)) + +} + +.getDeviceLoc <- function(x, units = ""npc"") { + xPth <- grid.grep(x, viewports = TRUE, global = TRUE)[[1]] + depth <- downViewport(attr(xPth, ""vpPath"")) + xGrb <- grid.get(xPth) + loc <- deviceLoc(xGrb$x, xGrb$y) + upViewport(depth) + loc +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/plotting-pieGrob.R",".R","4018","135","##----------------------------------------------------------------------------## +## pieGrob +##----------------------------------------------------------------------------## + +#' @name pieGrob +#' @title Create a pie grob +#' @description Create a pie grob +#' @param rads Numeric, radius values for each slice from 0 to 1 +#' @param fills Colors to fill the slices +#' @param wts Numeric, the relative portion of each slice +#' @param name,vp,gp Passed to [grid::gTree] +#' +#' @details +#' The default coloring can be set with `options(""txp.fills"")`. +#' +#' +#' @examples +#' library(grid) +#' +#' s <- seq(0.2, 1, by = 0.1) +#' grid.newpage() +#' grid.pieGrob(rads = s) +#' grid.newpage() +#' grid.pieGrob(rads = s, wts = s) +#' +#' curr_txp_fills <- options()$txp.fills +#' options(txp.fills = 1:8) +#' grid.newpage() +#' grid.pieGrob(rads = s) +#' options(txp.fills = curr_txp_fills) +#' +#' ## Can edit +#' grid.newpage() +#' grid.pieGrob(rads = s, name = ""myPie"") +#' grid.ls() ## show the grid elements +#' grid.edit(""myPie"", fills = 1:9, wts = 9:1) +#' +#' @return `pieGrob` [grid::grob] object +#' +#' @import grid +#' @export + +pieGrob <- function(rads, fills = NULL, wts = NULL, + name = NULL, vp = NULL, gp = NULL) { + pieVp <- makePieViewport() + gTree(name = name, + rads = rads, + fills = fills, + wts = wts, + gp = gp, + vp = vp, + childrenvp = pieVp, + children = makePieGrob(rads = rads, + fills = fills, + wts = wts, + vp = pieVp), + cl = ""pieGrob"") +} + +#' @rdname pieGrob +#' @export + +grid.pieGrob <- function(rads, fills = NULL, wts = NULL, + name = NULL, vp = NULL, gp = NULL) { + g <- pieGrob(rads = rads, + fills = fills, + wts = wts, + name = name, + vp = vp, + gp = gp) + grid.draw(g) +} + +#' @export + +editDetails.pieGrob <- function(x, specs) { + if (any(c(""rads"", ""fills"", ""wts"") %in% names(specs))) { + newRads <- if (is.null(specs$rads)) x$rads else specs$rads + newFills <- if (is.null(specs$fills)) x$fills else specs$fills + newWts <- if (is.null(specs$wts)) x$wts else specs$wts + x <- setChildren(x, + makePieGrob(rads = newRads, + fills = newFills, + wts = newWts, + vp = x$childrenvp)) + } + x +} + +makeSliceGrob <- function(rad, th0, th1, fill, name = NULL, vp = NULL) { + th <- c(seq(th0, th1, by = pi/360), th1) + x <- c(0, cos(th))*rad + y <- c(0, sin(th))*rad + polygonGrob(x = x, + y = y, + name = name, + gp = gpar(fill = fill, col = NA), + default.units = ""native"", + vp = vp) +} + +makePieGrob <- function(rads, fills = NULL, wts = NULL, vp = NULL) { + nSlices <- length(rads) + if (is.null(wts)) wts <- rep(1, nSlices) + wts <- wts/sum(wts) + ths <- cumsum(c(0, 2*pi*wts)) + + if (is.null(fills)) fills <- getOption(""txp.fills"", TXP_FILLS) + if (nSlices > length(fills)) fills <- colorRampPalette(fills)(nSlices) + if (nSlices < length(fills)) fills <- fills[1:nSlices] + + slices <- vector(""list"", nSlices) + for (i in seq_along(rads)) { + slices[[i]] <- makeSliceGrob(rad = rads[i], + th0 = ths[i], + th1 = ths[i + 1], + fill = fills[i], + name = gPath(sprintf(""slice%s"", i)), + vp = vp) + } + do.call(""gList"", slices) +} + +makePieViewport <- function() { + vpStack(viewport(layout = grid.layout(nrow = 1, ncol = 1, respect = TRUE)), + viewport(name = ""pievp"", + layout.pos.row = 1, + layout.pos.col = 1, + xscale = c(-1, 1), + yscale = c(-1, 1))) +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/plotting-boxLegendGrob.R",".R","1952","54","##----------------------------------------------------------------------------## +## boxLegendGrob +##----------------------------------------------------------------------------## + +#' @name boxLegendGrob +#' @title Create a filled-box legend +#' @description Create a filled-box legend +#' @param labels Character, the legend labels +#' @param fills Colors to fill the slices +#' @param name,vp,gp Passed to [grid::frameGrob] +#' +#' @details +#' Not yet exported. Need to break out the creation of viewports and grobs as +#' done in the exported grobs. This will allow better grobEdit methods, which +#' also needs to be created for the boxLegendGrob. +#' Also need to do some input checks. +#' +#' Also, if \code{grid::legendGrob} gets updated to use the 'has.fill' option +#' this function should be removed and \code{grid::legendGrob} can be used +#' instead. +#' +#' @import grid + +boxLegendGrob <- function(labels, fills, name = NULL, vp = NULL, gp = NULL) { + + wids <- c(unit(1.5, ""char""), unit(max(nchar(labels)), ""char"")) + hgts <- unit(rep_len(1.5, length(labels)), ""char"") + fg <- frameGrob(layout = grid.layout(ncol = 2, + nrow = length(labels), + widths = wids, + heights = hgts), + vp = vp, + name = name, + gp = gp) + for (i in seq_along(labels)) { + fg <- placeGrob(frame = fg, + grob = textGrob(label = labels[i]), + col = 2, + row = i) + fg <- placeGrob(frame = fg, + grob = rectGrob(width = unit(1, ""char""), + height = unit(1, ""char""), + gp = gpar(fill = fills[i], col = NA)), + col = 1, + row = i) + } + + fg + +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/plotting-pieGridGrob.R",".R","6522","188","##----------------------------------------------------------------------------## +## pieGridGrob +##----------------------------------------------------------------------------## + +#' @name pieGridGrob +#' @title Make grid of pieGrobs +#' @description Make grid of pieGrobs +#' +#' @param radMat `matrix()`, observations by slice radii +#' @param wts `vector()`, relative weights of each slice +#' @param fills Vector of colors to fill slices +#' @param labels `vector()`, (optional) label for each observation +#' @param showRadSum Logical scalar, when `TRUE` show the weighted sum of slices +#' below the label +#' @param nrow,ncol Integer scalar, number of rows and columns for the grid +#' @param byrow Logical scalar, fill the grid by rows when `TRUE` +#' @param name,gp,vp Passed to [grid::gTree] +#' +#' @examples +#' \donttest{ +#' library(grid) +#' +#' s <- seq(0.2, 1, by = 0.1) +#' smat <- do.call(""rbind"", replicate(20, s, simplify = FALSE)) +#' grid.newpage() +#' grid.pieGridGrob(radMat = smat) +#' +#' rownames(smat) <- sprintf(""obs%02d"", 1:20) +#' grid.newpage() +#' grid.pieGridGrob(radMat = smat, wts = s) +#' grid.newpage() +#' grid.pieGridGrob(radMat = smat, wts = s, showRadSum = TRUE, labels = FALSE) +#' grid.newpage() +#' grid.pieGridGrob(radMat = smat, labels = ""hello"") +#' grid.newpage() +#' grid.pieGridGrob(radMat = smat, labels = 1:20) +#' +#' ## Can edit like normal grid objects +#' grid.newpage() +#' grid.pieGridGrob(radMat = smat, wts = s, showRadSum = TRUE) +#' grid.ls() ## shows grid elements +#' grid.edit(""pie-20"", fills = 1:9) +#' grid.edit(""pie-19-label"", gp = gpar(font = 2, col = ""red"")) +#' grid.edit(""pie-1"", wts = rep(1, 9), rads = rep(1, 9)) +#' for (s in sprintf(""pie-%d-radSum"", 2:4)) { +#' grid.edit(s, gp = gpar(font = 2, col = ""blue"")) +#' } +#' } +#' +#' @return `pieGrob` [grid::grob] object +#' +#' @import grid +#' @importFrom rlang is_scalar_integerish is_scalar_logical +#' @importFrom grDevices colorRampPalette +#' @export + +pieGridGrob <- function(radMat, wts = NULL, fills = NULL, labels = NULL, + showRadSum = FALSE, ncol = NULL, nrow = NULL, + byrow = TRUE, name = NULL, gp = NULL, vp = NULL) { + + nPie <- NROW(radMat) + if (is.null(wts)) wts <- rep(1, NCOL(radMat)) + wts <- wts/sum(wts) + if (is.null(labels) || (is.logical(labels) && labels)) { + labels <- rownames(radMat) + } else { + if (is.logical(labels) && !labels) labels <- NULL + } + pos <- makePieGridPos(nPie = nPie, nrow = nrow, ncol = ncol, byrow = byrow) + pieGridVp <- makePieGridViewport(pos = pos, nPie = nPie) + gTree(radMat = radMat, + wts = wts, + fills = fills, + labels = labels, + nPie = nPie, + pos = pos, + name = name, + gp = gp, + vp = vp, + children = makePieGridGrob(radMat = radMat, + pos = pos, + wts = wts, + fills = fills, + labels = labels, + showRadSum = showRadSum, + vp = pieGridVp), + childrenvp = pieGridVp, + cls = ""pieGridGrob"") + +} + +#' @rdname pieGridGrob +#' @export + +grid.pieGridGrob <- function(radMat, wts = NULL, fills = NULL, labels = NULL, + showRadSum = FALSE, ncol = NULL, nrow = NULL, + byrow = TRUE, name = NULL, gp = NULL, vp = NULL) { + g <- pieGridGrob(radMat = radMat, + wts = wts, + fills = fills, + labels = labels, + showRadSum = showRadSum, + ncol = ncol, + nrow = nrow, + byrow = byrow, + name = name, + vp = vp, + gp = gp) + grid.draw(g) +} + +makePieGridPos <- function(nPie, nrow = NULL, ncol = NULL, byrow = TRUE) { + stopifnot(is_scalar_integerish(nPie)) + stopifnot(is.null(ncol) || is_scalar_integerish(ncol)) + stopifnot(is.null(nrow) || is_scalar_integerish(nrow)) + stopifnot(is_scalar_logical(byrow)) + if (is.null(nrow) && is.null(ncol)) { + ncol <- ceiling(sqrt(nPie)) + nrow <- ceiling(nPie/ncol) + } else { + if (is.null(nrow)) nrow <- ceiling(nPie/ncol) + if (is.null(ncol)) ncol <- ceiling(nPie/nrow) + } + + if(byrow) { + pos <- expand.grid(col = 1:ncol, row = 1:nrow) + } else { + pos <- expand.grid(row = 1:nrow, col = 1:ncol) + } + pos +} + +makePieGridViewport <- function(pos, nPie) { + nrow <- max(pos$row) + ncol <- max(pos$col) + gl <- grid.layout(nrow = nrow, + ncol = ncol, + widths = unit(rep_len(1, ncol), ""null""), + heights = unit(rep(1, nrow), ""null"")) + gridVp <- viewport(layout = gl) + pieBoxes <- vector(""list"", nPie) + for (i in 1:nPie) { + pieBoxes[[i]] <- viewport(name = sprintf(""pieBox-%s"", i), + layout.pos.row = pos[i, ""row""], + layout.pos.col = pos[i, ""col""]) + } + vpTree(gridVp, do.call(""vpList"", pieBoxes)) +} + +makePieGridGrob <- function(radMat, pos, wts = NULL, fills = NULL, + labels = NULL, showRadSum = FALSE, vp = NULL) { + + nPie <- NROW(radMat) + pies <- vector(""list"", nPie) + + for (i in 1:nPie) { + rads <- radMat[i, ] + pies[[i]] <- frameGrob(vp = vpStack(vp$parent, vp$children[[i]])) + pies[[i]] <- packGrob(frame = pies[[i]], + grob = pieGrob(rads = rads, + fills = fills, + wts = wts, + name = sprintf(""pie-%s"", i))) + if (showRadSum) { + rsum <- round(sum(rads*wts, na.rm = TRUE), 4) + pies[[i]] <- packGrob(frame = pies[[i]], + grob = textGrob(label = rsum, + name = sprintf(""pie-%s-radSum"", i)), + side = ""top"", + height = unit(1.15, units = ""char"")) + } + + if (!is.null(labels)) { + pies[[i]] <- packGrob(frame = pies[[i]], + grob = textGrob(label = labels[i], + name = sprintf(""pie-%s-label"", i)), + side = ""top"", + height = unit(1.15, units = ""char"")) + } + } + + do.call(""gList"", pies) + +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpResultList.R",".R","2547","98","##----------------------------------------------------------------------------## +## methods-txpResultList +##----------------------------------------------------------------------------## + +#' @name TxpResultList-class +#' @title List of TxpResult objects +#' @description Extension of [S4Vectors::SimpleList] that holds only [TxpResult] +#' objects. +#' +#' @param ... [TxpResult] object to create `TxpResultList` object +#' @param x `TxpResultList` object +#' +#' @template roxgn-loadExamples +#' @template roxgn-calcTxpModelList +#' +#' @seealso [TxpResult], [txpCalculateScores] +#' +#' @examples +#' ## duplicated +#' duplicated(resLst) +#' +#' ## Coercion +#' as(list(resLst[[1]], resLst[[2]]), ""TxpResultList"") +#' as.TxpResultList(list(res1 = resLst[[1]], res2 = resLst[[2]])) +#' +#' as(resLst[[1]], ""TxpResultList"") +#' as.TxpResultList(resLst[[1]]) + +NULL + +##----------------------------------------------------------------------------## +## constructor + +#' @rdname TxpResultList-class +#' @export + +TxpResultList <- function(...) { + listData <- list(...) + new2(""TxpResultList"", listData) +} + +##----------------------------------------------------------------------------## +## validity + +.TxpResultList.validity <- function(object) { + msg <- NULL + valid <- vapply(object@listData, is, logical(1), ""TxpResult"") + if (any(!valid)) { + msg <- c(msg, ""All TxpResult objects must be of class 'TxpResult.'"") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpResultList"", .TxpResultList.validity) + +##----------------------------------------------------------------------------## +## show + +.TxpResultList.show <- function(object) { + lnms <- .listDisplayNames(object) + .coolcat("" TxpResultList of length %d: %s\n"", lnms) +} + +setMethod(""show"", ""TxpResultList"", .TxpResultList.show) + +##----------------------------------------------------------------------------## +## duplicated + +#' @rdname TxpResultList-class +#' @export + +setMethod(""duplicated"", ""TxpResultList"", function(x) .dupList(x)) + +##----------------------------------------------------------------------------## +## coercion + +.TxpResultList.from.list <- function(from) { + do.call(""TxpResultList"", from) +} + +setAs(""list"", ""TxpResultList"", .TxpResultList.from.list) + +.TxpResultList.from.TxpResult <- function(from) { + TxpResultList(from) +} + +setAs(""TxpResult"", ""TxpResultList"", .TxpResultList.from.TxpResult) + +#' @rdname TxpResultList-class +#' @export + +as.TxpResultList <- function(x) as(x, ""TxpResultList"") + +##----------------------------------------------------------------------------## + + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpSliceList.R",".R","3789","126","##----------------------------------------------------------------------------## +## methods-txpSliceList +##----------------------------------------------------------------------------## + +#' @name TxpSliceList-class +#' @title List of TxpSlice objects +#' @description Extension of [S4Vectors::SimpleList] that requires +#' uniquely-named elements and holds only [TxpSlice] objects. +#' +#' @param ... [TxpSlice] object to create `TxpSliceList` object; MUST give +#' unique names to each slice +#' @param x `TxpSliceList` object +#' @param simplify Scalar logical, when `TRUE` the returned `list` is simplified +#' to a `vector`/[TxpTransFuncList] object +#' +#' @details +#' Note, there is no coercion for [TxpSlice] to `TxpSliceList` because unique +#' names are required. +#' +#' @examples +#' ## Create TxpSlice objects +#' s1 <- TxpSlice(""input1"", list(linear = function(x) x)) +#' s2 <- TxpSlice(c(""input2"", ""input3""), +#' list(log = function(x) log(x), sqrt = function(x) sqrt(x))) +#' +#' ## Create TxpSliceList +#' sl <- TxpSliceList(s1 = s1, s2 = s2) +#' +#' ## Accessors +#' txpValueNames(sl) +#' txpValueNames(sl, simplify = TRUE) +#' +#' txpTransFuncs(sl) +#' txpTransFuncs(sl, simplify = TRUE) +#' +#' ## Coercion +#' as(list(s1 = TxpSlice(""hello""), s2 = TxpSlice(""user"")), ""TxpSliceList"") +#' as.TxpSliceList(c(s1 = TxpSlice(""hello""), s2 = TxpSlice(""user""))) +#' +#' ## Concatenation +#' c(sl, TxpSliceList(s3 = TxpSlice(""input4""))) +#' +#' ## Reduce TxpSliceList to single slice +#' Reduce(merge, sl) + +NULL + +##----------------------------------------------------------------------------## +## constructor + +#' @rdname TxpSliceList-class +#' @export + +TxpSliceList <- function(...) { + listData <- list(...) + new2(""TxpSliceList"", listData) +} + +##----------------------------------------------------------------------------## +## validity + +.TxpSliceList.validity <- function(object) { + msg <- NULL + valid <- vapply(object@listData, is, logical(1), ""TxpSlice"") + if (any(!valid)) { + msg <- c(msg, ""All TxpSlice objects must be of class 'TxpSlice.'"") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpSliceList"", .TxpSliceList.validity) + +##----------------------------------------------------------------------------## +## accessors + +#' @describeIn TxpSliceList-class Return `list` of `txpValueNames` slots for the +#' contained [TxpSlice] objects, or `vector` when `simplify = TRUE` +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpValueNames"", ""TxpSliceList"", function(x, simplify = FALSE) { + stopifnot(is_scalar_logical(simplify)) + nms <- lapply(x, txpValueNames) + if (simplify) nms <- unlist(nms) + nms +}) + +#' @describeIn TxpSliceList-class Return `list` of `txpTransFuncs` slots for the +#' contained [TxpSlice] objects, or [TxpTransFuncList] when `simplify = TRUE` +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpTransFuncs"", ""TxpSliceList"", function(x, simplify = FALSE) { + stopifnot(is_scalar_logical(simplify)) + fxs <- lapply(x, txpTransFuncs) + if (simplify) fxs <- Reduce(c, fxs) + fxs +}) + +##----------------------------------------------------------------------------## +## duplicated + +#' @describeIn TxpSliceList-class Returns logical vector of `length(x)`, where +#' `TRUE` indicates a duplicate slice in the list; see [base::duplicated] +#' @export + +setMethod(""duplicated"", ""TxpSliceList"", function(x) .dupList(x)) + +##----------------------------------------------------------------------------## +## coercion + +.TxpSliceList.from.list <- function(from) { + do.call(""TxpSliceList"", from) +} + +setAs(""list"", ""TxpSliceList"", .TxpSliceList.from.list) + +#' @rdname TxpSliceList-class +#' @export + +as.TxpSliceList <- function(x) as(x, ""TxpSliceList"") + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpTransFuncList.R",".R","3612","122","##----------------------------------------------------------------------------## +## methods-txpTransFuncList +##----------------------------------------------------------------------------## + +#' @name TxpTransFuncList-class +#' @title List of TxpTransFunc objects +#' @description Extension of [S4Vectors::SimpleList] that holds only `NULL` or +#' [TxpTransFunc] objects. +#' +#' @param ... [TxpTransFunc] object or function to create `TxpTransFuncList` +#' object +#' @param x `list`, `function`, or [TxpTransFunc] object to coerce to +#' `TxpTransFuncList` +#' +#' @details +#' When `...` includes function objects, `TxpTransFuncList` will attempt to +#' coerce them to [TxpTransFunc] and return an error if any of the elements +#' cannot be coerced to [TxpTransFunc]. +#' +#' @examples +#' ## Create TxpTransFunc objects +#' tf1 <- TxpTransFunc(function(x) x) +#' tf2 <- TxpTransFunc(function(x) sqrt(x)) +#' +#' ## Create TxpTransFuncList +#' tfl <- TxpTransFuncList(linear = tf1, sqrt = tf2, cube = function(x) x^3) +#' tfl[[3]](3) == 27 +#' tfl[[""sqrt""]](4) == 2 +#' +#' ## Concatenate +#' c(tfl, tfl) +#' +#' ## names +#' names(c(tfl, tfl)) +#' +#' # note: names are printed as '' when missing; NULL is printed when list item +#' # is NULL +#' names(TxpTransFuncList(function(x) x, NULL)) +#' TxpTransFuncList(function(x) x, NULL) +#' +#' ## coercion +#' as(function(x) x, ""TxpTransFuncList"") +#' as.TxpTransFuncList(function(x) x) +#' +#' as(TxpTransFunc(function(x) x), ""TxpTransFuncList"") +#' as.TxpTransFuncList(TxpTransFunc(function(x) x)) +#' +#' as(list(function(x) x, sqrt = function(x) sqrt(x)), ""TxpTransFuncList"") +#' as.TxpTransFuncList(list(function(x) x, sqrt = function(x) sqrt(x))) + +NULL + +##----------------------------------------------------------------------------## +## constructor + +.TxpTransFuncList.toTransFunc <- function(x) { + if (!is.null(x) && !inherits(x, ""TxpTransFunc"")) { + x <- try(TxpTransFunc(x), silent = TRUE) + } + x +} + +#' @rdname TxpTransFuncList-class +#' @export + +TxpTransFuncList <- function(...) { + listData <- lapply(list(...), .TxpTransFuncList.toTransFunc) + valid <- vapply(listData, is, logical(1), ""TxpTransFunc_OR_NULL"") + if (any(!valid)) { + stop(""Some of the given list items could not be coerced to 'TxpTransFunc'."") + } + new2(""TxpTransFuncList"", listData) +} + +##----------------------------------------------------------------------------## +## validity + +.TxpTransFuncList.validity <- function(object) { + msg <- NULL + valid <- vapply(object@listData, is, logical(1), ""TxpTransFunc_OR_NULL"") + if (any(!valid)) { + msg <- c(msg, ""All TxpFuncList objects must be of class 'TxpTransFunc.'"") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpTransFuncList"", .TxpTransFuncList.validity) + +##----------------------------------------------------------------------------## +## show + +.TxpTransFuncList.show <- function(object) { + lnms <- .listDisplayNames(object) + .coolcat("" TxpTransFuncList of length %d: %s\n"", lnms) +} + +setMethod(""show"", ""TxpTransFuncList"", .TxpTransFuncList.show) + +##----------------------------------------------------------------------------## +## coercion + +.TxpTransFuncList.from.list <- function(from) { + do.call(""TxpTransFuncList"", from) +} + +setAs(""list"", ""TxpTransFuncList"", .TxpTransFuncList.from.list) + +.TxpTransFuncList.from.func <- function(from) { + TxpTransFuncList(from) +} + +setAs(""function"", ""TxpTransFuncList"", .TxpTransFuncList.from.func) + +#' @rdname TxpTransFuncList-class +#' @export + +as.TxpTransFuncList <- function(x) as(x, ""TxpTransFuncList"") + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/allGenerics.R",".R","2279","73","#' @importFrom BiocGenerics updateObject +#' @importFrom BiocGenerics sort +#' @importFrom BiocGenerics duplicated +#' @importFrom BiocGenerics as.data.frame + +#' @name txpGenerics +#' @title toxpiR package generics +#' @description toxpiR package generics; see class man pages for associated +#' methods +#' @param x toxpiR S4 object +#' @param value Replacement value +#' @param ... Included for extendability; not currently used +#' +#' @return See specific methods for details. + +NULL + +#' @rdname txpGenerics +setGeneric(""txpValueNames"", function(x, ...) standardGeneric(""txpValueNames"")) + +#' @rdname txpGenerics +setGeneric(""txpValueNames<-"", + function(x, ..., value) standardGeneric(""txpValueNames<-"")) + +#' @rdname txpGenerics +setGeneric(""txpTransFuncs"", function(x, ...) standardGeneric(""txpTransFuncs"")) + +#' @rdname txpGenerics +setGeneric(""txpTransFuncs<-"", + function(x, ..., value) standardGeneric(""txpTransFuncs<-"")) + +#' @rdname txpGenerics +setGeneric(""txpSlices"", function(x, ...) standardGeneric(""txpSlices"")) + +#' @rdname txpGenerics +setGeneric(""txpSlices<-"", + function(x, ..., value) standardGeneric(""txpSlices<-"")) + +#' @rdname txpGenerics +setGeneric(""txpWeights"", function(x, ...) standardGeneric(""txpWeights"")) + +#' @rdname txpGenerics +setGeneric(""txpWeights<-"", + function(x, ..., value) standardGeneric(""txpWeights<-"")) + +#' @rdname txpCalculateScores +setGeneric(""txpCalculateScores"", + function(model, input, ...) standardGeneric(""txpCalculateScores"")) + +#' @rdname txpGenerics +setGeneric(""txpScores"", function(x, ...) standardGeneric(""txpScores"")) + +#' @rdname txpGenerics +setGeneric(""txpSliceScores"", function(x, ...) standardGeneric(""txpSliceScores"")) + +#' @rdname txpGenerics +setGeneric(""txpModel"", function(x, ...) standardGeneric(""txpModel"")) + +#' @rdname txpGenerics +setGeneric(""txpIDs"", function(x, ...) standardGeneric(""txpIDs"")) + +#' @rdname txpGenerics +setGeneric(""txpIDs<-"", function(x, ..., value) standardGeneric(""txpIDs<-"")) + +#' @rdname txpGenerics +setGeneric(""txpRanks"", function(x, ...) standardGeneric(""txpRanks"")) + +#' @rdname txpGenerics +setGeneric(""txpMissing"", function(x, ...) standardGeneric(""txpMissing"")) + +#' @rdname txpGenerics +setGeneric(""txpResultParam"", function(x, ...) standardGeneric(""txpResultParam"")) +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpSlice.R",".R","5614","189","##----------------------------------------------------------------------------## +## methods-Slice +##----------------------------------------------------------------------------## + +#' @name TxpSlice-class +#' @title ToxPi Slice +#' @description S4 class to store ToxPi slices +#' +#' @slot txpValueNames `vector()` specifying the input columns to +#' include in the slice +#' @slot txpTransFuncs [TxpTransFuncList] with one function per entry in +#' `txpValueNames` or an object that can be coerced to `TxpTransFuncList`; +#' when `NULL`, no transformation function applied +#' +#' +#' @param txpValueNames Passed to `txpValueNames` slot +#' @param txpTransFuncs Passed to `txpTransFuncs` slot +#' @param x,y `TxpSlice` object +#' @param value Replacement value +#' +#' @details +#' If the user supplies `txpTransFuncs` a single function/[TxpTransFunc] object, +#' the given function will be recycled for each input with a warning. +#' +#' @examples +#' ## Create TxpSlice object +#' # Without transform functions +#' TxpSlice(txpValueNames = c(""sqrData"", ""expData"")) +#' # With transform functions +#' TxpSlice(txpValueNames = c(""sqrData"", ""expData""), +#' txpTransFuncs = c(sq = function(x) x^2, log = function(x) log(x))) +#' +#' # Transformation function recycled with warning when single function given +#' TxpSlice(txpValueNames = c(""sqrData"", ""expData""), +#' txpTransFuncs = function(x) x^2) +#' +#' +#' ## Access TxpSlice slots +#' sl <- TxpSlice(txpValueNames = c(""sqrData"", ""expData""), +#' txpTransFuncs = c(sq = function(x) x^2, +#' log = function(x) log(x))) +#' txpValueNames(sl) +#' txpTransFuncs(sl) +#' +#' ## Replacement +#' txpValueNames(sl)[1] <- ""hello"" +#' sl +#' +#' txpTransFuncs(sl)[[2]](exp(1)) +#' txpTransFuncs(sl)[[2]] <- function(x) sqrt(x) +#' txpTransFuncs(sl)[[2]](exp(1)) +#' +#' # Note that replacing a single list element does NOT update the name +#' sl +#' names(txpTransFuncs(sl))[2] <- ""sqrt"" +#' sl +#' +#' # Replacing the whole list DOES update the names +#' txpTransFuncs(sl) <- list(sqrt = function(x) sqrt(x), +#' log = function(x) log(x)) +#' sl +#' +#' ## length -- returns number of inputs +#' length(TxpSlice(letters)) +#' +#' ## merge +#' s1 <- TxpSlice(""hello"") +#' s2 <- TxpSlice(""data"") +#' merge(s1, s2) +#' +#' # Note, input names still must be unique +#' \dontrun{merge(s1, s1)} ## produces error + +NULL + +##----------------------------------------------------------------------------## +## constructor + +.TxpSlice.handle.funcs <- function(vn, tf) { + vnl <- length(vn) + if (is.null(tf)) tf <- vector(""list"", vnl) + if (class(tf) %in% c(""function"", ""TxpTransFunc"") && vnl > 1) { + warning(""Recycling given 'txpTransFuncs' for each input."") + tf <- .repFunc(tf, vnl) + } + if (!is(tf, ""TxpTransFuncList"")) { + tf <- as.TxpTransFuncList(tf) + } + tf +} + +#' @rdname TxpSlice-class +#' @export + +TxpSlice <- function(txpValueNames, txpTransFuncs = NULL) { + txpTransFuncs <- .TxpSlice.handle.funcs(txpValueNames, txpTransFuncs) + new2(""TxpSlice"", txpValueNames = txpValueNames, txpTransFuncs = txpTransFuncs) +} + +##----------------------------------------------------------------------------## +## accessors + +#' @describeIn TxpSlice-class Return `txpValueNames` slot +#' @export + +setMethod(""txpValueNames"", ""TxpSlice"", function(x) { x@txpValueNames }) + +#' @rdname TxpSlice-class +#' @export + +setReplaceMethod(""txpValueNames"", ""TxpSlice"", function(x, value) { + x@txpValueNames <- value + validObject(x) + x +}) + +#' @describeIn TxpSlice-class Return `txpTransFuncs` slot +#' @export + +setMethod(""txpTransFuncs"", ""TxpSlice"", function(x) { x@txpTransFuncs }) + +#' @rdname TxpSlice-class +#' @export + +setReplaceMethod(""txpTransFuncs"", ""TxpSlice"", function(x, value) { + value <- .TxpSlice.handle.funcs(txpValueNames(x), value) + x@txpTransFuncs <- value + validObject(x) + x +}) + +#' @describeIn TxpSlice-class Return number of inputs in slice; shortcut for +#' `length(txpValueNames(x))` +#' @export + +setMethod(""length"", ""TxpSlice"", function(x) { length(txpValueNames(x)) }) + +##----------------------------------------------------------------------------## +## validity + +.TxpSlice.validity <- function(object) { + msg <- NULL + vl <- txpValueNames(object) + fx <- txpTransFuncs(object) + if (any(duplicated(vl))) { + msg <- c(msg, ""txpValueNames() must be unique."") + } + if (length(vl) != length(fx)) { + tmp <- paste(""length(txpValueNames()) !="", + ""length(txpTransFuncs())"") + msg <- c(msg, tmp) + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpSlice"", .TxpSlice.validity) + +##----------------------------------------------------------------------------## +## show + +.TxpSlice.show <- function(object) { + n <- length(txpValueNames(object)) + cat(sprintf(""TxpSlice with %d input%s.\n"", n, ifelse(n > 1, ""s"", """"))) + .coolcat("" txpValueNames(%d): %s\n"", txpValueNames(object)) + fnms <- .listDisplayNames(txpTransFuncs(object)) + .coolcat("" txpTransFuncs(%d): %s\n"", fnms) +} + +setMethod(""show"", ""TxpSlice"", .TxpSlice.show) + +##----------------------------------------------------------------------------## +## merge + +.TxpSlice.merge <- function(x, y) { + vns <- c(txpValueNames(x), txpValueNames(y)) + tfs <- c(txpTransFuncs(x), txpTransFuncs(y)) + TxpSlice(txpValueNames = vns, txpTransFuncs = tfs) +} + +#' @describeIn TxpSlice-class Merge two `TxpSlice` objects into a single +#' slice +#' @export + +setMethod(""merge"", c(""TxpSlice"", ""TxpSlice""), .TxpSlice.merge) + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpModelList.R",".R","4396","144","##----------------------------------------------------------------------------## +## methods-txpModelList +##----------------------------------------------------------------------------## + +#' @name TxpModelList-class +#' @title List of TxpModel objects +#' @description Extension of [S4Vectors::SimpleList] that holds only [TxpModel] +#' objects. +#' +#' @param ... [TxpModel] object to create `TxpModelList` object +#' @param x `TxpModelList` object +#' +#' @examples +#' ## Create some TxpModel objects; see ?TxpModel for more details +#' s1 <- list(S1 = TxpSlice(""inpt1""), S2 = TxpSlice(""inpt2"")) +#' tf <- list(NULL, sqrt = function(x) sqrt(x)) +#' m1 <- TxpModel(txpSlices = s1, txpWeights = 2:1, txpTransFuncs = tf) +#' m2 <- m1 +#' txpSlices(m2) <- list(S3 = TxpSlice(""inpt3""), S4 = TxpSlice(""inpt4"")) +#' m3 <- merge(m1, m2) +#' +#' ## Build a TxpModelList object +#' TxpModelList(m1 = m1, m2 = m2, m3 = m3) +#' +#' ## Note: names are printed as '' when all are NULL +#' TxpModelList(m1, m2, m3) +#' names(TxpModelList(m1, m2, m3)) +#' +#' ## Test for duplicates +#' duplicated(TxpModelList(m1 = m1, m2 = m2, m3 = m3)) +#' duplicated(TxpModelList(m1 = m1, m2 = m1, m3 = m3)) +#' +#' ## Coerce lists/TxpModel objects to TxpModelList +#' as(list(m1 = m1, m2 = m2, m3 = m3), ""TxpModelList"") +#' as.TxpModelList(list(m1 = m1, m2 = m2, m3 = m3)) +#' +#' as(m1, ""TxpModelList"") +#' as.TxpModelList(m1) + +NULL + +##----------------------------------------------------------------------------## +## constructor + +#' @rdname TxpModelList-class +#' @export + +TxpModelList <- function(...) { + listData <- list(...) + new2(""TxpModelList"", listData) +} + +##----------------------------------------------------------------------------## +## validity + +.TxpModelList.validity <- function(object) { + msg <- NULL + valid <- vapply(object@listData, is, logical(1), ""TxpModel"") + if (any(!valid)) { + msg <- c(msg, ""All TxpModel objects must be of class 'TxpModel.'"") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpModelList"", .TxpModelList.validity) + +##----------------------------------------------------------------------------## +## txpCalculateScores + +.TxpModelList.calc <- function(model, input, + id.var = NULL, + rank.ties.method = c(""average"", ""first"", ""last"", + ""random"", ""max"", ""min""), + negative.value.handling = c(""keep"", ""missing"")) { + if (is.list(model)) { + model <- try(as.TxpModelList(model), silent = TRUE) + if (is(model, ""try-error"")) { + stop(""Given list could not be coerced to TxpModelList"") + } + } + resLst <- lapply(model, .calculateScores, + input = input, + id.var = id.var, + rank.ties.method = rank.ties.method, + negative.value.handling = negative.value.handling) + as.TxpResultList(resLst) +} + +#' @rdname txpCalculateScores +#' @export + +setMethod(""txpCalculateScores"", + c(""TxpModelList"", ""data.frame""), + .TxpModelList.calc) + +#' @rdname txpCalculateScores +#' @export + +setMethod(""txpCalculateScores"", c(""list"", ""data.frame""), .TxpModelList.calc) + +##----------------------------------------------------------------------------## +## show + +.TxpModelList.show <- function(object) { + lnms <- .listDisplayNames(object) + .coolcat("" TxpModelList of length %d: %s\n"", lnms) +} + +setMethod(""show"", ""TxpModelList"", .TxpModelList.show) + +##----------------------------------------------------------------------------## +## duplicated + +#' @describeIn TxpModelList-class Returns logical vector of `length(x)`, where +#' `TRUE` indicates a duplicate model in the list; see [base::duplicated] +#' @export + +setMethod(""duplicated"", ""TxpModelList"", function(x) .dupList(x)) + +##----------------------------------------------------------------------------## +## coercion + +.TxpModelList.from.list <- function(from) { + do.call(""TxpModelList"", from) +} + +setAs(""list"", ""TxpModelList"", .TxpModelList.from.list) + +.TxpModelList.from.TxpModel <- function(from) { + TxpModelList(from) +} + +setAs(""TxpModel"", ""TxpModelList"", .TxpModelList.from.TxpModel) + +#' @describeIn TxpModelList-class Coerce list or [TxpModel] objects to +#' TxpModelList +#' @export + +as.TxpModelList <- function(x) as(x, ""TxpModelList"") + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/allClasses.R",".R","3732","131","##----------------------------------------------------------------------------## +## All classes +##----------------------------------------------------------------------------## + +#' @import methods +#' @importFrom S4Vectors setValidity2 new2 +#' @importClassesFrom S4Vectors character_OR_NULL + +NULL + +##----------------------------------------------------------------------------## +## Virtual classes + +#' @importClassesFrom S4Vectors SimpleList +#' @importClassesFrom S4Vectors List +#' @importFrom S4Vectors List + +setClass(""NamedList"", contains = c(""VIRTUAL"", ""SimpleList"")) + +##----------------------------------------------------------------------------## +## TxpTransFunc + +#' @rdname TxpTransFunc-class +#' @exportClass TxpTransFunc + +setClass(""TxpTransFunc"", contains = ""function"", prototype = function(x) x) + +setClassUnion(""TxpTransFunc_OR_NULL"", members = c(""TxpTransFunc"", ""NULL"")) + +##----------------------------------------------------------------------------## +## TxpTransFuncList + +#' @rdname TxpTransFuncList-class +#' @exportClass TxpTransFuncList + +setClass(""TxpTransFuncList"", + contains = ""SimpleList"", + prototype = prototype(elementType = ""TxpTransFunc_OR_NULL"")) + +##----------------------------------------------------------------------------## +## TxpSlice + +#' @rdname TxpSlice-class +#' @exportClass TxpSlice + +setClass(""TxpSlice"", + slots = c(txpValueNames = ""character"", + txpTransFuncs = ""TxpTransFuncList"")) + +setClassUnion(""TxpSlice_OR_NULL"", members = c(""TxpSlice"", ""NULL"")) + +##----------------------------------------------------------------------------## +## TxpSliceList + +#' @rdname TxpSliceList-class +#' @importClassesFrom S4Vectors SimpleList +#' @exportClass TxpSliceList + +setClass(""TxpSliceList"", + contains = ""NamedList"", + prototype = prototype(elementType = ""TxpSlice"")) + +##----------------------------------------------------------------------------## +## TxpModel + +#' @rdname TxpModel-class +#' @exportClass TxpModel + +setClass(""TxpModel"", + slots = c(txpSlices = ""TxpSliceList"", + txpWeights = ""numeric"", + txpTransFuncs = ""TxpTransFuncList"")) + +setClassUnion(""TxpModel_OR_NULL"", members = c(""TxpModel"", ""NULL"")) + +##----------------------------------------------------------------------------## +## TxpModelList + +#' @rdname TxpModelList-class +#' @importClassesFrom S4Vectors SimpleList +#' @exportClass TxpModelList + +setClass(""TxpModelList"", + contains = ""SimpleList"", + prototype = prototype(elementType = ""TxpModel"")) + +##----------------------------------------------------------------------------## +## TxpResultParam + +#' @name TxpResultParam-class +#' @exportClass TxpResultParam + +setClass(""TxpResultParam"", + slots = c(rank.ties.method = ""character"", + negative.value.handling = ""character"")) + +##----------------------------------------------------------------------------## +## TxpResult + +#' @name TxpResult-class +#' @exportClass TxpResult + +setClass(""TxpResult"", + slots = c(txpScores = ""numeric"", + txpSliceScores = ""matrix"", + txpRanks = ""numeric"", + txpMissing = ""numeric"", + txpModel = ""TxpModel"", + txpIDs = ""character_OR_NULL"", + txpResultParam = ""TxpResultParam"")) + +setClassUnion(""TxpResult_OR_NULL"", members = c(""TxpResult"", ""NULL"")) + +##----------------------------------------------------------------------------## +## TxpResultList + +#' @rdname TxpResultList-class +#' @importClassesFrom S4Vectors SimpleList +#' @exportClass TxpResultList + +setClass(""TxpResultList"", + contains = ""SimpleList"", + prototype = prototype(elementType = ""TxpResult"")) + + + + + + + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpModel.R",".R","7524","259","##----------------------------------------------------------------------------## +## methods-TxpModel +##----------------------------------------------------------------------------## + +#' @name TxpModel-class +#' @title ToxPi Model +#' @description S4 class to store ToxPi models +#' +#' @slot txpSlices [TxpSliceList] object +#' @slot txpWeights numeric vector specifying the relative weight of each slice; +#' when NULL, defaults to 1 (equal weighting) for each slice +#' @slot txpTransFuncs [TxpTransFuncList] object (or list of functions +#' coercible to TxpTransFuncList) +#' +#' @param txpSlices Passed to `txpSlices` slot +#' @param txpWeights Passed to `txpWeights` slot +#' @param txpTransFuncs Passed to `txpTransFuncs` slot +#' @param x,y TxpModel object +#' @param value Replacement value +#' @param adjusted Scalar logical, when `TRUE` weights are adjusted to sum to 1 +#' @param simplify Scalar logical, when `TRUE` the returned `list` is simplified +#' +#' @examples +#' ## Create TxpSliceList & TxpTransFuncList objects +#' s1 <- list(S1 = TxpSlice(""inpt1""), S2 = TxpSlice(""inpt2"")) +#' tf <- list(NULL, sqrt = function(x) sqrt(x)) +#' +#' ## Create TxpModel object +#' m1 <- TxpModel(txpSlices = s1, txpWeights = 2:1, txpTransFuncs = tf) +#' m1 +#' +#' ## Access TxpModel slots +#' txpSlices(m1) +#' txpWeights(m1) +#' txpWeights(m1, adjusted = TRUE) +#' txpTransFuncs(m1) +#' +#' ## length +#' length(m1) ## equal to length(txpSlices(m1)) +#' length(m1) == length(txpSlices(m1)) +#' +#' ## names +#' names(m1) ## equal to names(txpSlices(m1)) +#' all(names(m1) == names(txpSlices(m1))) +#' +#' ## Replacement +#' m2 <- m1 +#' txpSlices(m2) <- list(S3 = TxpSlice(""inpt3""), S4 = TxpSlice(""inpt4"")) +#' m2 +#' names(m2)[2] <- ""hello"" +#' names(m2) +#' txpTransFuncs(m2) <- NULL +#' m2 +#' txpTransFuncs(m2)[[1]] <- function(x) x^2 +#' names(txpTransFuncs(m2))[1] <- ""sq"" +#' m2 +#' +#' ## merge +#' m3 <- merge(m1, m2) +#' m3 + +NULL + +##----------------------------------------------------------------------------## +## constructor + +#' @rdname TxpModel-class +#' @export + +TxpModel <- function(txpSlices, txpWeights = NULL, txpTransFuncs = NULL) { + if (!is(txpSlices, ""TxpSliceList"")) txpSlices <- as.TxpSliceList(txpSlices) + n <- length(txpSlices) + if (is.null(txpWeights)) txpWeights <- rep(1, n) + if (is.null(txpTransFuncs)) { + txpTransFuncs <- as(List(vector(""list"", n)), ""TxpTransFuncList"") + } + if (!is(txpTransFuncs, ""TxpTransFuncList"")) { + txpTransFuncs <- as.TxpTransFuncList(txpTransFuncs) + } + new2(""TxpModel"", + txpSlices = txpSlices, + txpWeights = txpWeights, + txpTransFuncs = txpTransFuncs) +} + +##----------------------------------------------------------------------------## +## accessors + +#' @describeIn TxpModel-class Return `txpSlices` slot +#' @aliases TxpModel-txpSlices +#' @export + +setMethod(""txpSlices"", ""TxpModel"", function(x) { + x@txpSlices +}) + +#' @rdname TxpModel-class +#' @export + +setReplaceMethod(""txpSlices"", ""TxpModel"", function(x, value) { + if (!is(value, ""TxpSliceList"")) value <- as.TxpSliceList(value) + x@txpSlices <- value + validObject(x) + x +}) + +#' @describeIn TxpModel-class Return `txpWeights` slot +#' @param adjusted Scalar logical, should the returned weights be adjusted +#' such that they sum to 1? +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpWeights"", ""TxpModel"", function(x, adjusted = FALSE) { + stopifnot(is_scalar_logical(adjusted)) + wts <- x@txpWeights + if (adjusted) wts <- wts/sum(wts) + wts +}) + +#' @rdname TxpModel-class +#' @export + +setReplaceMethod(""txpWeights"", ""TxpModel"", function(x, value) { + x@txpWeights <- value + validObject(x) + x +}) + +#' @describeIn TxpModel-class Return `txpTransFuncs` slot +#' @export + +setMethod(""txpTransFuncs"", ""TxpModel"", function(x) { + x@txpTransFuncs +}) + +#' @rdname TxpModel-class +#' @export + +setReplaceMethod(""txpTransFuncs"", ""TxpModel"", function(x, value) { + if (is.null(value)) value <- vector(""list"", length(x)) + if (!is(value, ""TxpTransFuncList"")) value <- as.TxpTransFuncList(value) + x@txpTransFuncs <- value + validObject(x) + x +}) + +#' @describeIn TxpModel-class Return `list` of `txpValueNames` slots for the +#' contained [TxpSliceList] object, or `vector` when `simplify = TRUE` +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpValueNames"", ""TxpModel"", function(x, simplify = FALSE) { + stopifnot(is_scalar_logical(simplify)) + nms <- txpValueNames(txpSlices(x), simplify = simplify) + nms +}) + +#' @describeIn TxpModel-class Return slice names; shortcut for +#' `names(txpSlices(x))` +#' @export + +setMethod(""names"", ""TxpModel"", function(x) { + names(txpSlices(x)) +}) + +#' @rdname TxpModel-class +#' @export + +setReplaceMethod(""names"", ""TxpModel"", function(x, value) { + names(x@txpSlices) <- value + validObject(x, complete = TRUE) + x +}) + +.TxpModel.calc <- function(model, input, + id.var = NULL, + rank.ties.method = c(""average"", ""first"", ""last"", + ""random"", ""max"", ""min""), + negative.value.handling = c(""keep"", ""missing"")) { + .calculateScores(model = model, + input = input, + id.var = id.var, + rank.ties.method = rank.ties.method, + negative.value.handling = negative.value.handling) +} + +#' @describeIn TxpModel-class Return number of slices in model; shortcut for +#' `length(txpSlices(x))` +#' @export + +setMethod(""length"", ""TxpModel"", function(x) { + length(txpSlices(x)) +}) + +#' @rdname txpCalculateScores +#' @export + +setMethod(""txpCalculateScores"", c(""TxpModel"", ""data.frame""), .TxpModel.calc) + +##----------------------------------------------------------------------------## +## validity + +.TxpModel.validity <- function(object) { + msg <- NULL + sl <- txpSlices(object) + wt <- txpWeights(object) + tf <- txpTransFuncs(object) + if (length(sl) != length(wt)) { + tmp <- ""length(txpSlices()) != length(txpWeights())"" + msg <- c(msg, tmp) + } + if (length(sl) != length(tf)) { + tmp <- ""length(txpSlices()) != length(txpTransFuncs())"" + msg <- c(msg, tmp) + } + valNms <- txpValueNames(sl, simplify = TRUE) + valDup <- duplicated(valNms) + if (any(valDup)) { + dup <- valNms[valDup] + wrn <- ""The following 'input' columns are duplicated in the model:\n %s"" + warning(sprintf(wrn, paste(dup, collapse = "", ""))) + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpModel"", .TxpModel.validity) + +##----------------------------------------------------------------------------## +## show + +.TxpModel.show <- function(object) { + fnms <- .listDisplayNames(txpTransFuncs(object)) + cat(sprintf(""TxpModel with %d slices.\n"", length(txpSlices(object)))) + .coolcat(""txpSlices(%d): %s\n"", names(txpSlices(object))) + .coolcat(""txpWeights(%d): %s\n"", txpWeights(object)) + .coolcat(""txpTransFuncs(%d): %s\n"", fnms) +} + +setMethod(""show"", ""TxpModel"", .TxpModel.show) + +##----------------------------------------------------------------------------## +## merge + +.TxpModel.merge <- function(x, y) { + sls <- c(txpSlices(x), txpSlices(y)) + wts <- c(txpWeights(x), txpWeights(y)) + tfs <- c(txpTransFuncs(x), txpTransFuncs(y)) + TxpModel(txpSlices = sls, txpWeights = wts, txpTransFuncs = tfs) +} + +#' @describeIn TxpModel-class Merge two `TxpModel` objects into a single +#' model +#' @export + +setMethod(""merge"", c(""TxpModel"", ""TxpModel""), .TxpModel.merge) + +##----------------------------------------------------------------------------## +","R" +"Toxicology","ToxPi/toxpiR","R/txpCalculateScores.R",".R","3760","123","##----------------------------------------------------------------------------## +## txpCalculateScores +##----------------------------------------------------------------------------## + +#' @name txpCalculateScores +#' @title Calculate ToxPi Scores for the given model and input data +#' @description Calculate ToxPi Scores for the given model and input data +#' +#' @param model [TxpModel] object or [TxpModelList] object +#' @param input data.frame object containing the model input data +#' @param id.var Character scalar, column in 'input' to store in +#' @inheritParams TxpResultParam-class +#' @inheritParams txpGenerics +#' +#' @details +#' `txpCalculateScores` is implemented as an S4 generic function with methods +#' for [TxpModel] and [TxpModelList]. +#' +#' Ranks are calculated such that the highest ToxPi score has a rank of 1. +#' +#' Missingness is determined after applying input-level transformations but +#' before applying slice-level transformations. +#' +#' @seealso [TxpModel], [TxpResult], [TxpResultParam] +#' +#' @template roxgn-loadExamples +#' @template roxgn-calcTxpModel +#' @template roxgn-calcTxpModelList +#' +#' @return [TxpResult] or [TxpResultList] object +#' +#' @export + +NULL + +.sumNA <- function(x) { + if (all(is.na(x))) return(NA_real_) + sum(x, na.rm = TRUE) +} + +.z2o <- function(x) { + (x - min(x, na.rm = TRUE))/diff(range(x, na.rm = TRUE)) +} + +.sumSlice <- function(slice, input, negative.value.handling) { + # Applies input-level transformation functions and sums the values to give + # a raw slice score + nms <- txpValueNames(slice) + dat <- input[nms] + if (negative.value.handling == ""missing"") dat[dat < 0] <- NA + tfs <- txpTransFuncs(slice) + for (i in seq_along(nms)) { + if (is.null(tfs[[i]])) next + dat[[i]] <- tfs[[i]](dat[[i]]) + } + x <- apply(dat, MARGIN = 1, .sumNA) + dat <- unlist(dat) + y <- sum(!is.finite(dat)) / length(dat) + list(sum = x, mis = y) +} + +.calculateScores <- function(model, input, + id.var = NULL, + rank.ties.method = c(""average"", ""first"", ""last"", + ""random"", ""max"", ""min""), + negative.value.handling = c(""keep"", ""missing"")) { + + ## Test inputs + .chkModelInput(model = model, input = input) + param <- TxpResultParam(rank.ties.method = rank.ties.method, + negative.value.handling = negative.value.handling) + + ## Clean up infinite in input + input <- .rmInfinite(model = model, input = input) + + ## Calculate raw slice scores and missingness + x <- lapply( + txpSlices(model), .sumSlice, input = input, + negative.value.handling = slot(param, ""negative.value.handling"")) + slc <- sapply(x, ""[["", ""sum"") + mis <- sapply(x, ""[["", ""mis"") + + ## Look for and apply slice-level transformation functions + tfs <- txpTransFuncs(model) + if (any(!sapply(tfs, is.null))) { + for (i in 1:ncol(slc)) { + if (is.null(tfs[[i]])) next + slc[ , i] <- tfs[[i]](slc[ , i]) + } + } + + ## Make infinite NaN + slc[is.infinite(slc)] <- NaN + + ## Scale slice scores from 0 to 1 + slc <- apply(slc, 2, .z2o) + + ## Make NA 0 + slc[is.na(slc)] <- 0 + + ## Calculate ToxPi score + wts <- txpWeights(model, adjusted = TRUE) + score <- rowSums(slc*rep(wts, each = NROW(slc)), na.rm = TRUE) + + ## Calculate ToxPi ranks + rnks <- rank(-score, ties.method = rank.ties.method) + + ## Assign IDs + ids <- if (!is.null(id.var)) as.character(input[[id.var]]) else NULL + + TxpResult(txpScores = score, + txpSliceScores = slc, + txpRanks = rnks, + txpMissing = mis, + txpModel = model, + txpIDs = ids, + txpResultParam = param) + +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-NamedList.R",".R","914","29","##----------------------------------------------------------------------------## +## methods-NamedList +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## validity + +#' @importFrom S4Vectors classNameForDisplay + +.NamedList.validity <- function(object) { + msg <- NULL + cname <- classNameForDisplay(object) + if (length(object) > 0 && is.null(names(object))) { + msg <- c(msg, sprintf(""%s must have names."", cname)) + } + if (any(duplicated(names(object)))) { + msg <- c(msg, sprintf(""%s names must be unique."", cname)) + } + if (any(is.na(names(object)))) { + msg <- c(msg, sprintf(""%s names must not be ."", cname)) + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""NamedList"", .NamedList.validity) + +##----------------------------------------------------------------------------## +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpResult.R",".R","11299","371","##----------------------------------------------------------------------------## +## methods-TxpResult +##----------------------------------------------------------------------------## + +#' @name TxpResult-class +#' @aliases TxpResult +#' @title ToxPi Result +#' @description S4 class to store ToxPi results +#' +#' @slot txpScores `vector()` of model scores +#' @slot txpSliceScores `matrix()`, sample by slice `matrix` with +#' individual slice scores +#' @slot txpRanks `vector()` with rank of scores +#' @slot txpMissing `vector()` with data missingness +#' @slot txpModel [TxpModel] object +#' @slot txpIDs `vector()` of observation IDs +#' @slot txpResultParam [TxpResultParam] object +#' +#' @param x [TxpResult] object +#' @param value Replacement value +#' @param adjusted Logical scalar, when `TRUE` the weights are adjusted to sum +#' to 1 or the slice scores are scaled to their respective weight +#' @param level `c('model', 'slices')`; indicates whether to retrieve +#' `txpTransFuncs` slot from the model or underlying slices +#' @param simplify Logical scalar, flatten `txpValueNames` or `txpTransFunc` +#' slots when retrieving slice-level information +#' @param i Subsetting index +#' @param j,drop,optional Not currently implemented +#' @param decreasing,na.last Passed to [base::sort] +#' @param row.names Passed to [base::data.frame] +#' @param id.name,score.name,rank.name Character scalar; when coercing to +#' [base::data.frame], the name for the `txpIDs`, `txpScores`, and `txpRanks` +#' columns, respectively +#' @param ... Passed to [base::data.frame] in `as.data.frame` or [base::sort] +#' in `sort` +#' +#' @seealso [txpCalculateScores], [plot], [TxpResultList] +#' +#' @template roxgn-loadExamples +#' @template roxgn-calcTxpModel +#' +#' @examples +#' ## Accessors +#' txpScores(res) +#' +#' txpSliceScores(res) ## adjusted for weight, by default +#' apply(txpSliceScores(res), 2, max, na.rm = TRUE) +#' +#' txpSliceScores(res, adjusted = FALSE) ## each score should have maximum of 1 +#' apply(txpSliceScores(res, adjusted = FALSE), 2, max, na.rm = TRUE) +#' +#' txpRanks(res) +#' +#' txpMissing(res) +#' +#' txpModel(res) +#' identical(txpModel(res), txp_example_model) +#' +#' txpIDs(res) +#' names(res) ## identical to txpIDs(res) +#' identical(txpIDs(res), names(res)) +#' +#' # Can access TxpModel slots directly +#' txpWeights(res) +#' txpWeights(res, adjusted = TRUE) +#' txpSlices(res) +#' # When retrieving transform functions, must specify level because both +#' # models and slices have transform functions +#' txpTransFuncs(res, level = ""model"") +#' +#' # Can access TxpSliceList slots directly +#' txpValueNames(res) +#' txpValueNames(res, simplify = TRUE) +#' txpTransFuncs(res, level = ""slices"") +#' txpTransFuncs(res, level = ""slices"", simplify = TRUE) +#' +#' ## Subsetting +#' res[1] +#' res[c(""chem01"", ""chem09"")] +#' res[grepl(""4|6"", txpIDs(res))] +#' \dontrun{ +#' res[c(TRUE, FALSE)] ## gets recycled with warning +#' } +#' +#' ## length -- returns number of observations +#' length(res) +#' length(res[1:5]) +#' +#' ## sort +#' names(res) +#' names(sort(res)) +#' +#' txpScores(res) +#' txpScores(sort(res)) +#' txpScores(sort(res, decreasing = FALSE)) +#' +#' ## as.data.frame +#' as.data.frame(res) +#' as.data.frame(res, id.name = ""nm"", score.name = ""scr"", rank.name = ""rnk"") + +NULL + +##----------------------------------------------------------------------------## +## constructor -- NOT exported + +TxpResult <- function(txpScores, txpSliceScores, txpRanks, txpMissing, + txpModel, txpIDs = NULL, txpResultParam) { + new2(""TxpResult"", + txpScores = txpScores, + txpSliceScores = txpSliceScores, + txpRanks = txpRanks, + txpMissing = txpMissing, + txpModel = txpModel, + txpIDs = txpIDs, + txpResultParam = txpResultParam) +} + +##----------------------------------------------------------------------------## +## accessors + +#' @describeIn TxpResult-class Return `txpScores` slot +#' @export + +setMethod(""txpScores"", ""TxpResult"", function(x) { x@txpScores }) + +#' @describeIn TxpResult-class Return `txpSliceScores` slot; default +#' `adjusted = TRUE`, i.e. return slice scores adjusted for weight +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpSliceScores"", ""TxpResult"", function(x, adjusted = TRUE) { + stopifnot(is_scalar_logical(adjusted)) + scr <- x@txpSliceScores + if (adjusted) { + wts <- txpWeights(x, adjusted = TRUE) + scr <- scr*rep(wts, each = NROW(scr)) + } + scr +}) + +#' @describeIn TxpResult-class Return `txpRanks` slot +#' @export + +setMethod(""txpRanks"", ""TxpResult"", function(x) { x@txpRanks }) + +#' @describeIn TxpResult-class Return `txpMissing` slot +#' @export + +setMethod(""txpMissing"", ""TxpResult"", function(x) { x@txpMissing }) + +#' @describeIn TxpResult-class Return `txpResultParam` slot +#' @export + +setMethod(""txpResultParam"", ""TxpResult"", function(x) { x@txpResultParam }) + +#' @describeIn TxpResult-class Return `txpModel` slot +#' @export + +setMethod(""txpModel"", ""TxpResult"", function(x) { x@txpModel }) + +#' @describeIn TxpResult-class Return `txpIDs` slot +#' @export + +setMethod(""txpIDs"", ""TxpResult"", function(x) { x@txpIDs }) + +.TxpResult.replaceIDs <- function(x, value) { + x@txpIDs <- value + validObject(x) + x +} + +#' @rdname TxpResult-class +#' @export + +setReplaceMethod(""txpIDs"", ""TxpResult"", .TxpResult.replaceIDs) + +#' @describeIn TxpResult-class Return `txpWeights` slot from model -- shortcut +#' for `txpWeights(txpModel(x))`; default `adjusted = FALSE`, i.e. return +#' unadjusted weights +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpWeights"", ""TxpResult"", function(x, adjusted = FALSE) { + stopifnot(is_scalar_logical(adjusted)) + txpWeights(txpModel(x), adjusted = adjusted) +}) + +#' @describeIn TxpResult-class Return `txpSlices` slot from model -- shortcut +#' for `txpSlices(txpModel(x))` +#' @export + +setMethod(""txpSlices"", ""TxpResult"", function(x) { txpSlices(txpModel(x)) }) + +.TxpResult.txpTransFuncs <- function(x, level, simplify = FALSE) { + stopifnot(is_scalar_logical(simplify)) + level <- match.arg(level, c(""model"", ""slices"")) + if (level == ""model"") { + return(txpTransFuncs(txpModel(x))) + } else { + return(txpTransFuncs(txpSlices(txpModel(x)), simplify = simplify)) + } +} + +#' @describeIn TxpResult-class Return `txpTransFuncs` slot from model -- +#' shortcut for `txpTransFuncs(txpModel(x))` +#' @importFrom rlang is_scalar_logical +#' @export + +setMethod(""txpTransFuncs"", ""TxpResult"", .TxpResult.txpTransFuncs) + +#' @describeIn TxpResult-class Return `txpValueNames` slot from slices -- +#' shortcut for `txpValueNames(txpSlices(txpModel(x)))` +#' @export + +setMethod(""txpValueNames"", ""TxpResult"", function(x, simplify = FALSE) { + txpValueNames(txpSlices(txpModel(x)), simplify = simplify) +}) + +.TxpResult.squareBracket <- function(x, i, j, ..., drop = FALSE) { + ss <- txpSliceScores(x, adjusted = FALSE)[i, , drop = FALSE] + TxpResult(txpScores = txpScores(x)[i], + txpSliceScores = ss, + txpRanks = txpRanks(x)[i], + txpMissing = txpMissing(x), + txpModel = txpModel(x), + txpIDs = txpIDs(x)[i], + txpResultParam = txpResultParam(x)) +} + +#' @rdname TxpResult-class +#' @export + +setMethod(""["", + c(""TxpResult"", ""logical"", ""missing""), + function(x, i, j, ..., drop = FALSE) { + if (length(i) < length(x)) { + warning(""Length of logical vector less than length of object; "", + ""recycling vector"") + } + .TxpResult.squareBracket(x, i) +}) + +#' @rdname TxpResult-class +#' @export + +setMethod(""["", c(""TxpResult"", ""integer"", ""missing""), .TxpResult.squareBracket) + +#' @rdname TxpResult-class +#' @export + +setMethod(""["", c(""TxpResult"", ""numeric"", ""missing""), .TxpResult.squareBracket) + +#' @rdname TxpResult-class +#' @export + +setMethod(""["", + c(""TxpResult"", ""character"", ""missing""), + function(x, i, j, ..., drop = FALSE) { + ids <- txpIDs(x) + if (is.null(ids)) { + stop(""TxpResult object must have assigned names, e.g. txpIDs(), to "", + ""susbet using a character vector."") + } + ind <- match(i, ids) + if (length(ind) == 1 && is.na(ind)) return(suppressWarnings(x[0])) + .TxpResult.squareBracket(x, ind) +}) + + +#' @describeIn TxpResult-class Return the number of observations; shortcut for +#' `length(txpScores(x))` +#' @export + +setMethod(""length"", ""TxpResult"", function(x) { length(txpScores(x)) }) + +#' @describeIn TxpResult-class Sort the ``TxpResult` object by their ranks +#' @export + +setMethod(""sort"", ""TxpResult"", function(x, decreasing = TRUE, + na.last = TRUE, ...) { + ind <- order(txpScores(x), decreasing = decreasing, na.last = na.last, ...) + x[ind] +}) + +#' @describeIn TxpResult-class Returns IDs; equal to `txpIDs(x)` +#' @export + +setMethod(""names"", ""TxpResult"", function(x) txpIDs(x)) + +#' @rdname TxpResult-class +#' @export + +setReplaceMethod(""names"", ""TxpResult"", .TxpResult.replaceIDs) + +##----------------------------------------------------------------------------## +## validity + +.TxpResult.validity <- function(object) { + msg <- NULL + scores <- txpScores(object) + sliceScores <- txpSliceScores(object, adjusted = FALSE) + model <- txpModel(object) + ids <- txpIDs(object) + if (!is(sliceScores[1], ""numeric"")) { + msg <- c(msg, ""Entries in txpSliceScores must be \""numeric\"""") + } + if (length(scores) != nrow(sliceScores)) { + msg <- c(msg, ""length(txpScores) != nrow(txpSliceScores)"") + } + if (!is.null(ids) && length(ids) != length(scores)) { + msg <- c(msg, ""length(txpIDs) != length(object)"") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpResult"", .TxpResult.validity) + +##----------------------------------------------------------------------------## +## coerce + +#' @importFrom rlang is_scalar_character is_scalar_logical + +.TxpResult.as.data.frame <- function(x, + row.names = NULL, + optional = FALSE, + ..., + id.name = ""id"", + score.name = ""score"", + rank.name = ""rank"", + adjusted = FALSE) { + stopifnot(is_scalar_character(id.name)) + stopifnot(is_scalar_character(score.name)) + stopifnot(is_scalar_character(rank.name)) + stopifnot(is_scalar_logical(adjusted)) + df <- as.data.frame(txpSliceScores(x, adjusted = adjusted), ...) + df[[score.name]] <- txpScores(x) + df[[rank.name]] <- txpRanks(x) + df[[id.name]] <- txpIDs(x) + outCols <- c(score.name, rank.name, names(txpSlices(x))) + if (!is.null(df[[id.name]])) { + outCols <- c(id.name, outCols) + } else { + warning(""txpIDs(x) is NULL; no ID column in returned data.frame."") + } + df[ , outCols] +} + +#' @describeIn TxpResult-class Coerce TxpResult to [base::data.frame] object +#' with IDs, scores, ranks, and slice scores +#' @export + +setMethod(""as.data.frame"", ""TxpResult"", .TxpResult.as.data.frame) + + +##----------------------------------------------------------------------------## +## show + +.TxpResult.show <- function(object) { + cat(sprintf(""TxpResult of length %s\n"", length(object))) + .coolcat(""names(%d): %s\n"", names(object)) +} + +setMethod(""show"", ""TxpResult"", .TxpResult.show) + + +##----------------------------------------------------------------------------## + + + +","R" +"Toxicology","ToxPi/toxpiR","R/utils.R",".R","3121","113","##---------------------------------------------------------------------------## +## Non-exported, non-documented, package-wide utility functions +##---------------------------------------------------------------------------## + +#' @importFrom S4Vectors coolcat + +.coolcat <- function(...) coolcat(..., indent = 2) + +.catslot <- function(x, object) { + cat("" "", x, "":"", "" "", slot(object = object, name = x), ""\n"", sep = """") +} + +.repFunc <- function(func, times) { + lst <- vector(mode = ""list"", length = times) + for (i in 1:times) lst[[i]] <- func + do.call(""TxpTransFuncList"", lst) +} + +.listDisplayNames <- function(x) { + n <- length(x) + lnms <- names(x) + if (is.null(lnms)) lnms <- rep('', n) + lnms[sapply(x, is.null)] <- ""NULL"" + lnms +} + +.dupList <- function(x) { + duplicated(as.list(x)) +} + +.chkModelInput <- function(model, input) { + stopifnot(is(model, ""TxpModel"")) + stopifnot(is.data.frame(input)) + valNms <- txpValueNames(model, simplify = TRUE) + inptNms <- names(input) + if (!all(valNms %in% inptNms)) { + miss <- valNms[!valNms %in% inptNms] + msg <- ""'input' missing the following data specified by 'model':\n %s"" + stop(sprintf(msg, paste(miss, collapse = "", ""))) + } + tstClass <- function(x) is.numeric(input[[x]]) + inptCls <- sapply(valNms, tstClass) + if (!all(inptCls)) { + nc2n <- valNms[!inptCls] + msg <- ""The following 'input' columns not numeric:\n %s"" + stop(sprintf(msg, paste(nc2n, collapse = "", ""))) + } +} + +.rmInfinite <- function(model, input) { + ## Clean up infinite in input + valNms <- txpValueNames(txpSlices(model), simplify = TRUE) + notFinite <- sapply(valNms, function(x) any(is.infinite(input[[x]]))) + if (any(notFinite)) { + warning(""Some of the given inputs contained infinite values."") + for (i in valNms[notFinite]) input[[i]][is.infinite(input[[i]])] <- NaN + } + input +} + +#' @importFrom grDevices col2rgb rgb + +.col2hex <- function(x) { + mat <- col2rgb(x) + rgb(red = mat[1, ], green = mat[2, ], blue = mat[3, ], maxColorValue = 255) +} + +# replicated pryr functions + +.to_env <- function(x, quiet = FALSE) { + if (is.environment(x)) { + x + } else if (is.list(x)) { + list2env(x) + } else if (is.function(x)) { + environment(x) + } else if (length(x) == 1 && is.character(x)) { + if (!quiet) message(""Using environment "", x) + as.environment(x) + } else if (length(x) == 1 && is.numeric(x) && x > 0) { + if (!quiet) message(""Using environment "", search()[x]) + as.environment(x) + } else { + stop(""Input can not be coerced to an environment"", call. = FALSE) + } +} + +.substitute_q <- function(x, env) { + stopifnot(is.language(x)) + env <- .to_env(env) + + call <- substitute(substitute(x, env), list(x = x)) + eval(call) + +} + +.make_function <- function(args, body, env = parent.frame()) { + args <- as.pairlist(args) + stopifnot( + .all_named(args), + is.language(body)) + env <- .to_env(env) + + eval(call(""function"", args, body), env) +} + +.all_named <- function(x) { + if (length(x) == 0) return(TRUE) + !is.null(names(x)) && all(names(x) != """") +} +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/txpImportGui.R",".R","4616","131","##----------------------------------------------------------------------------## +## txpImportGui +##----------------------------------------------------------------------------## + +#' @name txpImportGui +#' @title Import data file generated by ToxPi GUI +#' @description Import data file generated by ToxPi GUI +#' +#' @param guiDataFile Character scalar, the path to a 'data' export from the +#' ToxPi GUI +#' +#' @details +#' This function takes the '_data.csv' files generated by the GUI. +#' See \url{https://toxpi.github.io/} for more information. +#' +#' Because of the way toxpiR implements transformation functions, there is not +#' a way currently to use the GUI 'hitcount' function. +#' +#' @return `list` with `$model` containing [TxpModel] object; `$input` +#' containing `data.frame` with input data; `$fills` containing a vector +#' of fill colors. +#' +#' @importFrom utils type.convert read.csv +#' @export + +txpImportGui <- function(guiDataFile) { + + stopifnot(is_scalar_character(guiDataFile)) + stopifnot(file.exists(guiDataFile)) + + gui <- read.csv(guiDataFile, stringsAsFactors = FALSE, header = FALSE) + res <- try(.fromGui(gui), silent = TRUE) + if (is(res, ""try-error"")) stop(""The given 'guiDataFile' could not be parsed."") + if (is(res, ""simpleCondition"")) stop(conditionMessage(res)) + res + +} + +#' @importFrom tidyr separate +#' @importFrom rlang is_scalar_character + +.fromGui <- function(gui) { + + sliceInfoInd <- grepl('^#', gui[ , 1]) + infoNms <- c(""name"", ""wt"", ""col"", ""scale"") + sliceInfo <- tidyr::separate(data = gui[sliceInfoInd, ], + col = ""V1"", + into = infoNms, + sep = ""!"", + convert = FALSE) + sliceInfo$name <- sub('^#\\s+', '', sliceInfo$name) + sliceInfo$col <- sub('^0x', '#', sliceInfo$col) + sliceInfo$wt <- sapply(strsplit(sliceInfo$wt, split = '/'), function(x) { + as.numeric(x[1]) / as.numeric(ifelse(length(x) == 2, x[2], 1)) + }) + sliceInfo <- sliceInfo[ , infoNms] + validFuncs <- sliceInfo$scale %in% names(TXP_GUI_FUNCS) + if (!all(validFuncs)) { + f <- paste(sliceInfo$scale[!validFuncs], collapse = "", "") + msg <- sprintf(paste(""Given scaling function(s), '%s', not compatible with"", + ""toxpiR. See ?txpImportGui for more information.""), + f) + return(simpleCondition(msg)) + } + sliceInfo$ind <- apply(gui[sliceInfoInd, ], 1, function(x) which(x == ""x"")) + + inputStart <- which(grepl('^row$', gui[ , 1], ignore.case = TRUE)) + if (length(inputStart) != 1) { + inputStart <- which(gui[ , 1] == '') # Format D + } + inputNms <- as.character(gui[inputStart, ]) + input <- gui[(inputStart + 1):nrow(gui), ] + input[] <- lapply(input, type.convert, as.is = TRUE) + names(input) <- inputNms + input[input < 0] <- NA + row.names(input) <- 1:nrow(input) + + mkSl <- function(i) { + s <- TxpSlice(txpValueNames = inputNms[sliceInfo[i, ""ind""][[1]]]) + sl <- length(s) + tnm <- sliceInfo[i, ""scale""] + tfs <- .repFunc(TXP_GUI_FUNCS[[tnm]], sl) + names(tfs) <- rep(tnm, sl) + txpTransFuncs(s) <- tfs + s + } + + sliceLst <- lapply(seq(nrow(sliceInfo)), mkSl) + names(sliceLst) <- sliceInfo$name + sliceLst <- as.TxpSliceList(sliceLst) + + model <- TxpModel(txpSlices = sliceLst, txpWeights = sliceInfo[ , ""wt""]) + + vnms <- unique(txpValueNames(txpSlices(model), simplify = TRUE)) + numCols <- sapply(input[vnms], is.numeric) + if (!all(numCols)) { + cols <- paste(vnms[numCols], collapse = "", "") + msg <- sprintf(paste(""Following input column(s), '%s', could not be"", + ""coerced to numeric.""), + cols) + return(simpleCondition(msg)) + } + + list(model = model, input = input, fills = sliceInfo$col) + +} + +#' @importFrom stats sd + +TXP_GUI_FUNCS <- list( + 'linear(x)' = function(x) { x }, + 'hit count' = function(x) { as.integer(x != 0) }, + '-log10(x)' = function(x) { ifelse(x <= 0, NA, -log10(x)) }, + '-log10(x)+log10(max(x))' = function(x) { + ifelse(x <= 0, NA, -log10(x) + log10(max(x, na.rm = TRUE))) + }, + '-log10(x)+6' = function(x) { ifelse(x <= 0, NA, -log10(x) + 6) }, + '-ln(x)' = function(x) { ifelse(x <= 0, NA, -log(x)) }, + 'log10(x)' = function(x) { ifelse(x <= 0, NA, log10(x)) }, + 'sqrt(x)' = function(x) { sqrt(x) }, + 'zscore(x)' = function(x) { (x - mean(x, na.rm = TRUE))/sd(x, na.rm = TRUE) }, + 'uniform(x)' = function(x) { + xmn <- min(x, na.rm = TRUE) + xmx <- max(x, na.rm = TRUE) + (x - xmn)/(xmx - xmn) + } +) + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpTransFunc.R",".R","4011","129","##----------------------------------------------------------------------------## +## methods-TxpTransFunc +##----------------------------------------------------------------------------## + +#' @name TxpTransFunc-class +#' @title Numeric transformation function +#' @description S4 class to store numeric transformation functions +#' +#' @param x function, see details +#' +#' @details +#' \code{TxpTransFunc} inherits from a standard R function, but specifies a +#' single input and a numeric output of the same length. +#' +#' Functions can be passed directly to \code{TxpTransFuncList} list and the +#' functions will be coerced to \code{TxpTransFunc}. +#' +#' We have an imperfect system for dealing with primitive functions (e.g., +#' [base::sqrt]). +#' To coerce primitives to TxpTransFunc's, we wrap them in another function +#' cal; wrapping the primitives obscures the original function and requires +#' the user to explore the function environment to understand the primitive +#' called. +#' We recommend wrapping primitives in separate functions to make the intent +#' clear, .e.g., `mysqrt <- function(x) sqrt(x)`. +#' +#' @examples +#' f1 <- function(x) ""hello"" +#' f2 <- function(x) 3 +#' f3 <- function(x) x + 5 +#' \dontrun{ +#' t1 <- TxpTransFunc(x = f1) ## Produces error +#' t2 <- TxpTransFunc(x = f2) ## Produces error +#' } +#' t3 <- TxpTransFunc(x = f3) +#' +#' ## TxpTransFunc objects act as any other function +#' body(t3) +#' formals(t3) +#' t3(1:10) +#' +#' ## Coercion from functions +#' \dontrun{ +#' TxpTransFuncList(f1, f2, f3) ## Produces error because f1, f3 not valid +#' } + +NULL + +##----------------------------------------------------------------------------## +## constructor + +#' @rdname TxpTransFunc-class +#' @export + +TxpTransFunc <- function(x) { + if (missing(x)) return(new(""TxpTransFunc"")) + if (is.primitive(x)) { + somePrimitive <- x + f <- .convertPrimitive(somePrimitive) + } + else f <- x + new2(""TxpTransFunc"", f) +} + +##----------------------------------------------------------------------------## +## validity + +.TxpTransFunc.validity <- function(object) { + msg <- NULL + suppressWarnings({ + res1 <- try(object(1:5), silent = TRUE) + res2 <- try(object(1:6), silent = TRUE) + }) + if (is(res1, ""try-error"") || is(res2, ""try-error"")) { + msg <- c(msg, ""TxpTransFunc returned error when given numeric input."") + return(msg) + } + if (length(res1) != 5 || length(res2) != 6) { + msg <- c(msg, ""TxpTransFunc output length must equal input length."") + } + if (!class(res1) %in% c(""numeric"", ""integer"")) { + msg <- c(msg, ""TxpTransFunc output must be numeric for numeric inputs."") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(Class = ""TxpTransFunc"", method = .TxpTransFunc.validity) + +##----------------------------------------------------------------------------## +## coercion + +.TxpTransFunc.coerce.from.function <- function(from) { + if (is.primitive(from)) { + somePrimitive <- from + f <- .convertPrimitive(somePrimitive) + } + else f <- from + TxpTransFunc(f) +} + +setAs(""function"", ""TxpTransFunc"", .TxpTransFunc.coerce.from.function) + +##----------------------------------------------------------------------------## +## concatenation + +## Close, but rearranges the elements inappropriately: +# f <- TxpTransFunc(f) +# c(a = f, b = f, f) +## ALSO, causes errors with the 'c' method for TxpTransFuncList that would +## need correction +# .TxpTransFunc.concatenate <- function(x, ...) { +# lst <- if (missing(x)) list(...) else list(x, ...) +# do.call(""TxpTransFuncList"", lst) +# } +# setMethod(""c"", ""TxpTransFunc"", .TxpTransFunc.concatenate) + +##----------------------------------------------------------------------------## +## utilities +.convertPrimitive <- function(somePrimitive) { + warning(""Using primitive functions obscures behavior; "", + ""see ?TxpTransFunc for more details."") + f <- function(y) somePrimitive(y) + f <- .make_function(formals(f), .substitute_q(body(f), environment(f))) +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/plotting-annScatterGrob.R",".R","3420","95","##----------------------------------------------------------------------------## +## annScatterGrob -- not yet exported +##----------------------------------------------------------------------------## + +#' @importFrom grDevices extendrange +#' @import grid + +annScatterGrob <- function(x, y, ann = NULL, xlab = NULL, ylab = NULL, + xscale = NULL, yscale = NULL, + xaxis = TRUE, yaxis = TRUE, + margins = c(5.1, 4.1, 4.1, 2.1), + name = NULL, gp = NULL, vp = NULL, ...) { + + if (is.null(xscale)) xscale <- extendrange(range(x)) + if (is.null(yscale)) yscale <- extendrange(range(y)) + + pltVp <- plotViewport(margins = margins, name = ""annSctrPlotVp"") + datVp <- viewport(xscale = xscale, yscale = yscale, name = ""annSctrDataVp"") + annSctrVp <- vpTree(pltVp, vpList(datVp)) + annSctr <- makeAnnScatter(x = x, + y = y, + ann = ann, + xaxs = xaxis, + yaxs = yaxis, + xlab = xlab, + ylab = ylab, + vp = annSctrVp, + ...) + gTree(name = name, + ann = ann, + xscale = xscale, + yscale = yscale, + vp = vp, + childrenvp = annSctrVp, + children = annSctr, + cl = ""annScatterGrob"") + +} + +grid.annScatterGrob <- function(x, y, ann = NULL, xlab = NULL, ylab = NULL, + xscale = NULL, yscale = NULL, + xaxis = TRUE, yaxis = TRUE, + margins = c(5.1, 4.1, 4.1, 2.1), + name = NULL, gp = NULL, vp = NULL, ...) { + + g <- annScatterGrob(x = x, + y = y, + ann = ann, + xlab = xlab, + ylab = ylab, + xaxis = xaxis, + yaxis = yaxis, + xscale = xscale, + yscale = yscale, + margins = margins, + name = name, + gp = gp, + vp = vp, + ...) + grid.draw(g) + +} + +makeAnnScatter <- function(x, y, ann, xaxs, yaxs, xlab, ylab, vp, ...) { + + annLst <- vector(mode = ""list"", length = length(ann)) + nms <- names(ann) + if (is.null(nms)) nms <- sprintf(""ann-%s"", seq_along(ann)) + for (i in seq_along(ann)) { + ind <- ann[i] + annLst[[i]] <- nullGrob(x = unit(x[ind], ""native""), + y = unit(y[ind], ""native""), + name = nms[i]) + } + grbLst <- gList() + grbLst[['annotations']] <- gTree(name = ""annotations"", + vp = vp, + children = do.call(""gList"", annLst)) + grbLst[['sctr']] <- pointsGrob(x = x, y = y, vp = vp, ...) + if (xaxs) grbLst[['xaxs']] <- grid.xaxis(draw = FALSE, vp = vp) + if (yaxs) grbLst[['yaxs']] <- grid.yaxis(draw = FALSE, vp = vp) + if (!is.null(xlab)) { + grbLst[['xlab']] <- textGrob(xlab, y = unit(-3, ""line""), vp = vp) + } + if (!is.null(ylab)) { + grbLst[['ylab']] <- textGrob(ylab, + x = unit(-3, ""line""), + vp = vp, + rot = 90) + } + + grbLst + +} +","R" +"Toxicology","ToxPi/toxpiR","R/methods-TxpResultParam.R",".R","3228","91","##----------------------------------------------------------------------------## +## methods-TxpResultParam +##----------------------------------------------------------------------------## + +#' @name TxpResultParam-class +#' @aliases TxpResultParam +#' @title ToxPi Result Parameters +#' @description S4 class to store ToxPi result calculation parameters +#' +#' @slot rank.ties.method Character scalar, method used to calculate score +#' ranks passed to [base::rank] +#' @slot negative.value.handling Character scalar, how negative values are +#' handled, see details +#' +#' @param rank.ties.method Passed to `rank.ties.method` slot +#' @param negative.value.handling Passed to `negative.value.handling` slot +#' +#' @details +#' If more than one value is passed to `TxoResultParam` scalar options, e.g. +#' `rank.ties.method`, only the first value is kept. +#' +#' The `rank.ties.method` slot is passed to [base::rank] for calculating the +#' ranks of observations, with the highest-scoring observation having the rank +#' of 1. +#' +#' `negative.value.handling` indicates how to handle negative values in the +#' inputs. The ToxPi algorithm originally intended to accept non-negative +#' potency values; the GUI, therefore, treats negative values in the input as +#' missing. By default, [txpCalculateScores] keeps negative values +#' (`negative.value.handling = ""keep""`). To replicate the GUI behavior, users +#' can set `negative.value.handling = ""missing""`. +#' +#' @seealso [txpCalculateScores], [TxpResult] +#' + +NULL + +##----------------------------------------------------------------------------## +## constructor -- NOT exported + +TxpResultParam <- function(rank.ties.method, negative.value.handling) { + new2(""TxpResultParam"", + rank.ties.method = rank.ties.method[1], + negative.value.handling = negative.value.handling[1]) +} + +##----------------------------------------------------------------------------## +## validity + +#' @importFrom rlang is_scalar_character + +.TxpResultParam.validity <- function(object) { + msg <- NULL + rankMthd <- slot(object, ""rank.ties.method"") + if (!is_scalar_character(rankMthd)) { + msg <- c(msg, ""rank.ties.method must be scalar character"") + } + validRnkMthd <- c(""average"", ""first"", ""last"", ""random"", ""max"", ""min"") + if (is_scalar_character(rankMthd) && !rankMthd %in% validRnkMthd) { + msg <- c(msg, ""Invalid rank.ties.method; see ?base::rank"") + } + negHndl <- slot(object, ""negative.value.handling"") + if (!is_scalar_character(negHndl)) { + msg <- c(msg, ""negative.value.handling must be scalar character"") + } + validNegHndl <- c(""keep"", ""missing"") + if (is_scalar_character(negHndl) && !negHndl %in% validNegHndl) { + msg <- c(msg, ""Invalid negative.value.handling; see ?TxpResultParam"") + } + if (is.null(msg)) return(TRUE) + msg +} + +setValidity2(""TxpResultParam"", .TxpResultParam.validity) + +##----------------------------------------------------------------------------## +## show + +.TxpResultParam.show <- function(object) { + cat(""TxpResultParam:\n"") + sapply(names(getSlots(""TxpResultParam"")), .catslot, object = object) +} + +setMethod(""show"", ""TxpResultParam"", .TxpResultParam.show) + + +##----------------------------------------------------------------------------## + + + +","R" +"Toxicology","ToxPi/toxpiR","R/txpExportGui.R",".R","6008","159","##----------------------------------------------------------------------------## +## txpExportGui +##----------------------------------------------------------------------------## + +#' @name txpExportGui +#' @title Export comma-separated file intended for ToxPi GUI +#' @description Export comma-separated file intended for ToxPi GUI +#' +#' @param fileName Character scalar, the path to the output file +#' @inheritParams txpCalculateScores +#' @inheritParams pieGrob +#' +#' @details +#' The GUI differs in two meaninful ways for exporting `toxpiR` models: (1) the +#' GUI only allows for integer weights; (2) the GUI applies transformation +#' functions differently. +#' +#' `txpExporGui` will not work for models with non-integer weights. +#' +#' The GUI only applies a single transformation function to every input within +#' a slice, and only functions from a pre-determined list; `toxpiR` allows +#' users to apply any valid function individually to each input, then a second +#' transformation function on the summed slice values. Because of this +#' complexity, any exported models with slice-level transformation functions +#' will not export at the input level. In other words, the export will have only +#' the final slice scores. Otherwise, all input-level transformations will be +#' performed, the and the export will contain transformed input-level data with +#' the `linear(x)` GUI transformation. +#' +#' @importFrom rlang is_scalar_character +#' @importFrom utils write.table +#' @export + +txpExportGui <- function(fileName = ""txpModel.csv"", + input, + model, + id.var = NULL, + fills = NULL) { + + ## TODO: fileName checks, can it be written? does it already exist? etc. + + stopifnot(is_scalar_character(fileName)) + + ## Test inputs + .chkModelInput(model = model, input = input) + + ## Clean up infinite in input + input <- .rmInfinite(model, input) + + slcWts <- txpWeights(model) + if (any(slcWts%%1 != 0)) { + stop(""ToxPi GUI only allows integer weights in the model."") + } + + ## Check for slice-level transformations + tfs <- txpTransFuncs(model) + if (any(!sapply(tfs, is.null))) { + ## Output as completely transformed slice values + warning(""Model contains slice-level transformation; export will not "", + ""contain input-level data. See ?txpExportGui for more "", + ""information."") + res <- .calculateScores(model = model, input = input) + mat <- txpSliceScores(res) + slcVec <- vnmVec <- colnames(mat) + } else { + ## Notes: may duplicate inputs because the same input in different slices + ## can have different transformation functions + vnmVec <- txpValueNames(model, simplify = TRUE) + slcVec <- names(model) + vnmLst <- txpValueNames(model) + itfsLst <- txpTransFuncs(txpSlices(model)) + matLst <- list() + for (i in seq_along(vnmLst)) { + mat <- matrix(NA_real_, nrow = NROW(input), ncol = length(vnmLst[[i]])) + for (j in seq_along(vnmLst[[i]])) { + if (is.null(itfsLst[[i]][[j]])) { + mat[ , j] <- input[ , vnmLst[[i]][[j]]] + } else { + mat[ , j] <- itfsLst[[i]][[j]](input[ , vnmLst[[i]][[j]]]) + } + } + # Make sure transformed values are positive + minMat <- min(mat[is.finite(mat)]) + if (minMat < 0) { + x <- -floor(minMat) + # If slices contain multiple components and any missing values, then those + # missing values must be replaced with the added constant to produce the same + # slice/toxpi scores because slice scores are computed by sum not mean + # However, if all values are missing in a row, the leave it alone + if (ncol(mat) > 1 & any(!is.finite(mat))) { + idxNA <- apply(mat, 1, function(x) all(is.na(x))) + mat[!idxNA & !is.finite(mat)] <- 0 + warning(""Slice \"""", slcVec[i], ""\"" contains both missing and negative values "", + ""after applying transformations so missing values were replaced with 0 "", + ""and then all values were increased by x = "", x, ""."") + } else { + warning(""Slice \"""", slcVec[i], ""\"" contains negative values "", + ""after applying transformations so all values were increased by x = "", x, ""."") + } + # Shift all values by a constant to make them positive + mat <- mat + x + } + matLst[[i]] <- mat + } + mat <- do.call(cbind, matLst) + } + + ## Make infinite NaN + mat[is.infinite(mat)] <- NaN + + ## Determine colors + nSlices <- length(slcVec) + if (is.null(fills)) fills <- getOption(""txp.fills"", TXP_FILLS) + if (nSlices > length(fills)) fills <- colorRampPalette(fills)(nSlices) + if (nSlices < length(fills)) fills <- fills[1:nSlices] + + fills <- .col2hex(fills) + fills <- sub(""^#"", ""0x"", fills) + + ## Rename any duplicated column names + vnmLst <- txpValueNames(model) + if (any(duplicated(vnmVec))) { + dup <- unique(vnmVec[duplicated(vnmVec)]) + for (i in seq_along(vnmLst)) { + vnmLst[[i]] <- gsub(paste0('^(', paste(dup, collapse = '|'), ')$'), paste0('\\1_slice', i), vnmLst[[i]]) + } + vnmVec <- unlist(vnmLst) + } + + ## Prepare the header + slcMeta <- paste(slcVec, slcWts, fills, ""linear(x)"", sep = ""!"") + slcMeta <- paste(""#"", slcMeta) + slcVnmInd <- vector(mode = ""list"", length = nSlices) + names(slcVnmInd) <- slcVec + for (i in slcVec) { + slcVnmInd[[i]] <- rep('', length(vnmVec)) + slcVnmInd[[i]][vnmVec %in% vnmLst[[i]]] <- 'x' + } + hdr <- cbind(slcMeta, do.call(rbind, slcVnmInd)) + + ## Default names + ids <- if (is.null(id.var)) 1:NROW(input) else input[[id.var]] + + ## Make final output + out <- rbind(hdr, c('', vnmVec), cbind(ids, mat)) + + ## Write csv file + write.table(x = out, + file = fileName, + quote = FALSE, + sep = "","", + row.names = FALSE, + col.names = FALSE) + +} + +##----------------------------------------------------------------------------## + +","R" +"Toxicology","ToxPi/toxpiR","R/toxpiR-package.R",".R","1888","69","#' @keywords internal +""_PACKAGE"" + +## usethis namespace: start +## usethis namespace: end +NULL + +# TXP_FILLS = c(""dodgerblue"", +# ""bisque"", +# ""darkolivegreen3"", +# ""darkorchid3"", +# ""mistyrose2"", +# ""darkgoldenrod1"") +TXP_FILLS = c( + ""#f3622d"", + ""#fba71b"", + ""#57b757"", + ""#41a9c9"", + ""#4258c9"", + ""#9a42c8"", + ""#c84164"", + ""#888888"" +) + +#' @name toxpiR-datasets +#' @title toxpiR data objects +#' @description Objects included in the toxpiR package, loaded with +#' [utils::data] +#' @aliases txp_example_input txp_example_model +#' +#' @usage data(txp_example_input, package = ""toxpiR"") +#' @usage data(txp_example_model, package = ""toxpiR"") +#' +#' @section txp_example_input: +#' +#' Small example input data to be used with [txpCalculateScores] in creating +#' [TxpResult] objects. A [base::data.frame] with 10 rows and 9 variables +#' \describe{ +#' \item{name}{Observation names} +#' \item{metric#}{Input data for ToxPi models} +#' } +#' +#' @source +#' +#' @section txp_example_model: +#' +#' Example [TxpModel] object intended for `txp_example_data`; model with 4 +#' slices. +#' +#' @examples +#' data(txp_example_input, package = ""toxpiR"") +#' data(txp_example_model, package = ""toxpiR"") +#' txp_example_input +#' txp_example_model +#' +#' ## Code to create txp_example_model +#' tf1 <- TxpTransFuncList(linear = function(x) x) +#' sl <- TxpSliceList(s1 = TxpSlice(sprintf(""metric%d"", 1:2)), +#' s2 = TxpSlice(""metric3""), +#' s3 = TxpSlice(sprintf(""metric%d"", 4:7), +#' tf1[rep(""linear"", 4)]), +#' s4 = TxpSlice(""metric8"", tf1)) +#' tf2 <- TxpTransFuncList(NULL, linear = function(x) x, NULL, NULL) +#' TxpModel(txpSlices = sl, txpWeights = c(2, 1, 3, 2), txpTransFuncs = tf2) +#' +#' @importFrom utils data + +NULL +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat.R",".R","56","5","library(testthat) +library(toxpiR) + +test_check(""toxpiR"") +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpResult.R",".R","8788","201","##----------------------------------------------------------------------------## +## TxpResult/txpCalculateScores tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## txpCalculateScores + +test_that(""We can create TxpResult objects through txpCalculateScores"", { + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + expect_s4_class(res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name""), + ""TxpResult"") + inf_example <- txp_example_input + inf_example[""chem4"", ""metric1""] <- Inf + expect_warning(inf_res <- txpCalculateScores(model = txp_example_model, + input = inf_example, + id.var = ""name"")) + expect_s4_class(inf_res, ""TxpResult"") + txpValueNames(txpSlices(txp_example_model)[[2]]) <- ""notInput"" + expect_error(txpCalculateScores(model = txp_example_model, + input = txp_example_input)) + txp_example_input$notInput <- ""hello"" + expect_error(txpCalculateScores(model = txp_example_model, + input = txp_example_input)) +}) + +##----------------------------------------------------------------------------## +## Accessors + +test_that(""TxpResult accessors return expected slots"", { + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + expect_s4_class(res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name""), + ""TxpResult"") + expect_s4_class(txpModel(res), ""TxpModel"") + expect_type(txpScores(res), ""double"") + expect_type(txpIDs(res), ""character"") + expect_equal(txpIDs(res), sprintf(""chem%02d"", 1:10)) + expect_type(txpSliceScores(res), ""double"") + expect_true(is.matrix(txpSliceScores(res))) + expect_equal(dim(txpSliceScores(res)), c(10, 4)) + expect_equal(rowSums(txpSliceScores(res, adjusted = TRUE)), txpScores(res)) + expect_equal(apply(txpSliceScores(res, adjusted = FALSE), 2, max), + c(s1 = 1, s2 = 1, s3 = 1, s4 = 1)) + expect_equal(txpRanks(sort(res)), 1:10) + expect_equal(txpRanks(sort(res, decreasing = FALSE)), 10:1) + expect_s4_class(txpSlices(res), ""TxpSliceList"") + expect_length(txpSlices(res), 4) + expect_equal(round(txpScores(res), 6), + c(0.863316, 0.414845, 0.347997, 0.164044, 0.425231, + 0.585716, 0.000000, 0.719512, 0.771979, 0.470999)) + expect_equal(txpTransFuncs(res, level = ""model""), + txpTransFuncs(txpModel(res))) + expect_equal(txpTransFuncs(res, level = ""slices""), + txpTransFuncs(txpSlices(txpModel(res)))) + expect_equal(txpTransFuncs(res, level = ""slices"", simplify = TRUE), + txpTransFuncs(txpSlices(txpModel(res)), simplify = TRUE)) + expect_equal(txpValueNames(res), txpValueNames(txpSlices(txpModel(res)))) + expect_equal(txpValueNames(res, simplify = TRUE), + txpValueNames(txpSlices(txpModel(res)), simplify = TRUE)) + expect_type(txpMissing(res), ""double"") + expect_equal(length(txpMissing(res)), length(txpSlices(res))) + expect_true(all(txpMissing(res) >=0 & txpMissing(res) <=1)) + expect_equal(txpMissing(res), c(s1 = 0.1,s2 =0.1,s3 =0.125,s4 =0.1)) +}) + +##----------------------------------------------------------------------------## +## Replacement + +test_that(""We can replace TxpResult names/txpIDs"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name"") + oldNms <- names(res) + newNms <- as.character(sprintf(""new%02d"", 1:10)) + }) + expect_named({names(res) <- newNms; res}, newNms) + expect_named({txpIDs(res) <- oldNms; res}, oldNms) + expect_named({txpIDs(res)[1] <- ""hello""; res[1]}, ""hello"") + expect_named({names(res)[8:9] <- newNms[8:9]; res[8:9] }, newNms[8:9]) + expect_error(names(res) <- letters) +}) + +##----------------------------------------------------------------------------## +## Subsetting + +test_that(""TxpResult accessors return expected slots"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name"") + }) + expect_s4_class(res[1], ""TxpResult"") + expect_length(res[1], 1) + expect_named(res[1], ""chem01"") + expect_s4_class(res[c(rep(TRUE, 4), rep(FALSE, 6))], ""TxpResult"") + expect_length(res[c(rep(TRUE, 4), rep(FALSE, 6))], 4) + expect_named(res[c(rep(TRUE, 4), rep(FALSE, 6))], sprintf(""chem%02d"", 1:4)) + expect_s4_class(res[c(""chem04"", ""chem08"")], ""TxpResult"") + expect_length(res[c(""chem04"", ""chem08"")], 2) + expect_named(res[c(""chem04"", ""chem08"")], c(""chem04"", ""chem08"")) + expect_error(res[25]) + expect_warning(expect_length(res[c(TRUE, FALSE)], 5)) + expect_length(res[""notAName""], 0) + expect_silent(names(res) <- NULL) + expect_error(res[""hello""]) +}) + +##----------------------------------------------------------------------------## +## Coercion + +test_that(""We can coerce TxpResult to data.frame"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name"") + }) + expect_s3_class(as.data.frame(res), ""data.frame"") + expect_equal(dim(as.data.frame(res)), c(10, 7)) + expect_named(as.data.frame(res), + c(""id"", ""score"", ""rank"", sprintf(""s%d"", 1:4))) + expect_named(as.data.frame(res, + id.name = ""a"", + score.name = ""b"", + rank.name = ""c""), + c(""a"", ""b"", ""c"", sprintf(""s%d"", 1:4))) + txpIDs(res) <- NULL + expect_warning(woID <- as.data.frame(res)) + expect_s3_class(woID, ""data.frame"") + expect_named(woID, c(""score"", ""rank"", sprintf(""s%d"", 1:4))) +}) + +##----------------------------------------------------------------------------## +## Show + +test_that(""TxpResult show method displays correct information"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name"") + }) + expect_output(print(res), ""TxpResult of length 10"") + expect_output(print(res), ""chem01 chem02 ... chem09 chem10"") +}) + +##----------------------------------------------------------------------------## +## Plot -- TxpResult, missing + +test_that(""We can make and edit ToxPi diagrams"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name"") + }) + expect_silent(plot(res)) + expect_silent(grid.edit(""pie-1"", fills = NULL)) + grid.edit(""pie-10::slice1"", gp = gpar(fill = ""#7DBC3D"")) + expect_silent(plot(res, package = ""gg"")) + expect_silent(plot(res, package = ""gg"",fills = c(""red"",""blue"",""green"",""magenta""))) + expect_silent(plot(res, package = ""gg"",showScore = FALSE)) + expect_silent(plot(res, package = ""gg"",ncol = 2)) + expect_silent(plot(res, package = ""gg"",bgcolor = ""white"")) + expect_silent(plot(res, package = ""gg"",sliceBorderColor = NULL)) + expect_silent(plot(res, package = ""gg"",sliceValueColor = ""#FF00FF"",)) + expect_silent(plot(res, package = ""gg"",sliceLineColor = ""#FF00FF"")) + expect_silent(plot(res, package = ""gg"",showMissing = FALSE)) + expect_silent(plot(res, package = ""gg"",showCenter = FALSE)) +}) + +##----------------------------------------------------------------------------## +## Plot -- TxpResult, numeric + +test_that(""We can make ToxPi rank plot "", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + data(txp_example_model, package = ""toxpiR"") + res <- txpCalculateScores(model = txp_example_model, + input = txp_example_input, + id.var = ""name"") + }) + expect_silent(plot(res, txpRanks(res))) + expect_silent(plot(res, txpRanks(res), labels = 1:10)) +}) + + +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpSlice.R",".R","3229","81","##----------------------------------------------------------------------------## +## TxpSlice tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization + +test_that(""We can create TxpSlice objects"", { + vnames <- c(""input1"", ""input2"", ""input3"") + tfuncs <- TxpTransFuncList(f1 = TxpTransFunc(), f2 = NULL, f3 = NULL) + expect_s4_class(TxpSlice(txpValueNames = vnames), ""TxpSlice"") + expect_s4_class(TxpSlice(txpValueNames = vnames, txpTransFuncs = tfuncs), + ""TxpSlice"") + expect_warning(recycle <- TxpSlice(c(""a"", ""b"", ""c""), function(x) x)) + expect_s4_class(recycle, ""TxpSlice"") + expect_length(txpTransFuncs(recycle), 3) + expect_error(TxpSlice()) + expect_error(TxpSlice(NA)) + expect_error(TxpSlice(NULL)) + expect_error(TxpSlice(c(""x"", ""x""))) + expect_error(TxpSlice(vnames, tfuncs[1:2])) +}) + +##----------------------------------------------------------------------------## +## Accessors + +test_that(""TxpSlice accessors return expected slots"", { + sl <- TxpSlice(txpValueNames = c(""input1"", ""input2"", ""input3""), + txpTransFuncs = TxpTransFuncList(f1 = TxpTransFunc(), + f2 = NULL, + f3 = NULL)) + expect_s4_class(txpTransFuncs(sl), ""TxpTransFuncList"") + expect_equal(txpValueNames(sl), c(""input1"", ""input2"", ""input3"")) +}) + +##----------------------------------------------------------------------------## +## Replace + +test_that(""We can replace TxpSlice slots"", { + sl <- TxpSlice(""input1"") + expect_s4_class({txpValueNames(sl) <- ""input2""; sl}, ""TxpSlice"") + expect_equal(txpValueNames(sl), ""input2"") + expect_error(txpValueNames(sl) <- 3) + expect_error(txpValueNames(sl) <- c(""a"", ""b"")) + expect_s4_class({txpTransFuncs(sl) <- function(x) x; sl}, ""TxpSlice"") + expect_s4_class({names(txpTransFuncs(sl)) <- ""linear""; sl}, ""TxpSlice"") + expect_equal(txpTransFuncs(sl)[[1]](10), 10) + expect_named(txpTransFuncs(sl), ""linear"") +}) + + +##----------------------------------------------------------------------------## +## Show + +test_that(""TxpSlice shows correct information"", { + sl <- TxpSlice(c(""input1"", ""input2""), list(f1 = function(x) x, NULL)) + expect_output(print(sl), ""txpValueNames\\(2\\)"") + expect_output(print(sl), ""input1 input2"") + expect_output(print(sl), ""txpTransFuncs\\(2\\)"") + expect_output(print(sl), ""f1 NULL"") +}) + +##----------------------------------------------------------------------------## +## Length + +test_that(""TxpSlice length returns correct length"", { + expect_equal(length(TxpSlice(letters)), 26) + expect_equal(length(TxpSlice(letters[1:5])), 5) +}) + +##----------------------------------------------------------------------------## +## Merge + +test_that(""We can merge two TxpSlice objects"", { + s1 <- TxpSlice(c(""input1"", ""input2""), list(NULL, linear = function(x) x)) + s2 <- TxpSlice(c(""input3"", ""input4""), list(NULL, linear = function(x) x)) + expect_s4_class(smrg <- merge(s1, s2), ""TxpSlice"") + expect_equal(txpValueNames(smrg), c(""input1"", ""input2"", ""input3"", ""input4"")) + expect_named(txpTransFuncs(smrg), c("""", ""linear"", """", ""linear"")) +}) +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpTransFuncList.R",".R","2852","75","##----------------------------------------------------------------------------## +## TxpTransFuncList tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization + +test_that(""We can create TxpTransFuncList objects"", { + expect_s4_class(TxpTransFuncList(TxpTransFunc()), ""TxpTransFuncList"") + expect_s4_class(TxpTransFuncList(f = TxpTransFunc()), ""TxpTransFuncList"") + expect_s4_class(TxpTransFuncList(function(x) x), ""TxpTransFuncList"") + expect_s4_class(TxpTransFuncList(NULL), ""TxpTransFuncList"") + f <- function(x) x + expect_s4_class(l <- TxpTransFuncList(NULL, NULL, f1 = f, f, NULL), + ""TxpTransFuncList"") + expect_length(l, 5) + expect_named(l, c('', '', 'f1', '', '')) + expect_error(TxpTransFuncList(NULL, ""a"")) + expect_error(TxpTransFuncList(function(x) ""a"")) + expect_silent(l <- as.list(l)) + expect_s4_class(as.TxpTransFuncList(l), ""TxpTransFuncList"") + expect_s4_class(as(l, ""TxpTransFuncList""), ""TxpTransFuncList"") + expect_s4_class(as.TxpTransFuncList(function(x) x), ""TxpTransFuncList"") + expect_s4_class(as(function(x) x, ""TxpTransFuncList""), ""TxpTransFuncList"") +}) + +##----------------------------------------------------------------------------## +## Show + +test_that(""TxpTransFuncList show method displays correct information"", { + expect_silent(f <- function(x) x) + expect_silent(l <- TxpTransFuncList(NULL, NULL, f1 = f, f, NULL)) + expect_output(print(l), ""TxpTransFuncList of length 5"") + expect_output(print(l), ""NULL NULL f1 '' NULL"") + expect_silent(names(l) <- NULL) + expect_output(print(l), ""NULL NULL '' '' NULL"") +}) + +##----------------------------------------------------------------------------## +## Concatenation + +test_that(""We can concatenate TxpTransFuncList objects"", { + expect_silent({ + f <- TxpTransFunc() + l <- TxpTransFuncList(f = f, f, NULL) + }) + expect_s4_class(cl <- c(l, rev(l), l), ""TxpTransFuncList"") + expect_length(cl, 9) + expect_named(cl, c('f', '', '', '', '', 'f', 'f', '', '')) +}) + +##----------------------------------------------------------------------------## +## Replacement + +test_that(""We can replace TxpTransFuncList objects"", { + expect_silent({ + f <- TxpTransFunc() + l <- TxpTransFuncList(f = f, f, NULL) + }) + expect_s4_class({l[[2]] <- function(x) x^2; l}, ""TxpTransFuncList"") + expect_equal(l[[2]](10), 100) + expect_error(l[[2]] <- ""a"") + expect_error(l[[2]] <- function(x) x + ""hello"") + expect_s4_class({l[2:3] <- list(function(x) x, function(x) sqrt(x)); l}, + ""TxpTransFuncList"") + expect_equal(l[[2]](10), 10) + expect_equal(l[[3]](100), 10) + expect_length({l[2] <- list(NULL); l}, 3) + expect_output(print(l), ""f NULL ''"") + expect_length({l[[1]] <- NULL; l}, 2) + expect_output(print(l), ""NULL ''"") +}) + + +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpResultList.R",".R","5260","129","##----------------------------------------------------------------------------## +## TxpResultList tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization/txpCalculateScores + +test_that(""We can create TxpResultList objects through txpCalculateScores"", { + data(txp_example_input, package = ""toxpiR"") + sl <- TxpSliceList(s1 = TxpSlice(sprintf(""metric%d"", 1:2)), + s2 = TxpSlice(sprintf(""metric%d"", 3:7))) + md1 <- TxpModel(sl, txpWeights = c(2, 1)) + md2 <- TxpModel(sl) + md3 <- TxpModel(sl, + txpTransFuncs = list(f1 = TxpTransFunc(), + f2 = TxpTransFunc())) + ml <- TxpModelList(md1, md2, md3) + expect_s4_class(res <- txpCalculateScores(model = ml, + input = txp_example_input, + id.var = ""name""), + ""TxpResultList"") + expect_s4_class(txpCalculateScores(model = as.list(ml), + input = txp_example_input, + id.var = ""name""), + ""TxpResultList"") + expect_equal(txpModel(res[[1]]), md1) + expect_equal(txpModel(res[[2]]), md2) + expect_equal(txpModel(res[[3]]), md3) + expect_error(TxpResultList(NULL)) + expect_error(TxpResultList(NULL, res[[1]])) + expect_error(TxpResultList(1)) + expect_error(txpCalculateScores(model = c(as.list(ml), ""hello""), + input = txp_example_input, + id.var = ""name"")) +}) + +##----------------------------------------------------------------------------## +## Show + +test_that(""TxpResultList show method displays correct information"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + sl <- TxpSliceList(s1 = TxpSlice(sprintf(""metric%d"", 1:2)), + s2 = TxpSlice(sprintf(""metric%d"", 3:7))) + md1 <- TxpModel(sl, txpWeights = c(2, 1)) + md2 <- TxpModel(sl) + md3 <- TxpModel(sl, + txpTransFuncs = list(f1 = TxpTransFunc(), + f2 = TxpTransFunc())) + ml <- TxpModelList(md1, m2 = md2, md3) + l <- txpCalculateScores(model = ml, + input = txp_example_input, + id.var = ""name"") + }) + expect_output(print(l), ""TxpResultList of length 3"") + expect_output(print(l), ""'' m2 ''"") + expect_silent(names(l) <- NULL) + expect_output(print(l), ""'' '' ''"") +}) + +##----------------------------------------------------------------------------## +## Concatenation + +test_that(""We can concatenate TxpResultList objects"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + sl <- TxpSliceList(s1 = TxpSlice(sprintf(""metric%d"", 1:2)), + s2 = TxpSlice(sprintf(""metric%d"", 3:7))) + md1 <- TxpModel(sl, txpWeights = c(2, 1)) + md2 <- TxpModel(sl) + md3 <- TxpModel(sl, + txpTransFuncs = list(f1 = TxpTransFunc(), + f2 = TxpTransFunc())) + ml <- TxpModelList(m1 = md1, md2, m3 = md3) + l <- txpCalculateScores(model = ml, + input = txp_example_input, + id.var = ""name"") + }) + expect_s4_class(cl <- c(l, rev(l), l), ""TxpResultList"") + expect_length(cl, 9) + expect_named(cl, c('m1', '', 'm3', 'm3', '', 'm1', 'm1', '', 'm3')) +}) + +##----------------------------------------------------------------------------## +## Duplicated + +test_that(""We can detect duplicate TxpResult objects in TxpResultList"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + sl <- TxpSliceList(s1 = TxpSlice(sprintf(""metric%d"", 1:2)), + s2 = TxpSlice(sprintf(""metric%d"", 3:7))) + md1 <- TxpModel(sl, txpWeights = c(2, 1)) + md2 <- TxpModel(sl) + ml1 <- TxpModelList(m1 = md1, m2 = md1) + ml2 <- TxpModelList(m1 = md1, m2 = md2) + l1 <- txpCalculateScores(model = ml1, + input = txp_example_input, + id.var = ""name"") + l2 <- txpCalculateScores(model = ml2, + input = txp_example_input, + id.var = ""name"") + }) + expect_true(any(duplicated(l1))) + expect_false(any(duplicated(l2))) +}) + +##----------------------------------------------------------------------------## +## Coercion + +test_that(""We can coerce to TxpResultList objects"", { + expect_silent({ + data(txp_example_input, package = ""toxpiR"") + sl <- TxpSliceList(s1 = TxpSlice(sprintf(""metric%d"", 1:2)), + s2 = TxpSlice(sprintf(""metric%d"", 3:7))) + md1 <- TxpModel(sl, txpWeights = c(2, 1)) + md2 <- TxpModel(sl) + md3 <- TxpModel(sl, + txpTransFuncs = list(f1 = TxpTransFunc(), + f2 = TxpTransFunc())) + ml <- TxpModelList(m1 = md1, md2, m3 = md3) + l <- lapply(ml, txpCalculateScores, + input = txp_example_input, + id.var = ""name"") + }) + expect_s4_class(as.TxpResultList(l), ""TxpResultList"") + expect_s4_class(as.TxpResultList(l[[1]]), ""TxpResultList"") +}) + +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpSliceList.R",".R","3009","75","##----------------------------------------------------------------------------## +## TxpSliceList tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization + +test_that(""We can create TxpSliceList objects"", { + expect_s4_class(TxpSliceList(), ""TxpSliceList"") + expect_s4_class(TxpSliceList(S1 = TxpSlice(""inpt1""), S2 = TxpSlice(""inpt2"")), + ""TxpSliceList"") + expect_error(TxpSliceList(TxpSlice(""inpt1""))) + expect_error(TxpSliceList(S1 = TxpSlice(""inpt1""), S1 = TxpSlice(""inpt2""))) + expect_error(TxpSliceList(NULL)) + expect_error(TxpSliceList(""a"")) +}) + +test_that(""We can coerce list to TxpSliceList"", { + l <- list(S1 = TxpSlice(""inpt1""), S2 = TxpSlice(""inpt2"")) + expect_s4_class(as.TxpSliceList(l), ""TxpSliceList"") +}) + +##----------------------------------------------------------------------------## +## Accessors + +test_that(""We can access TxpSlice slots from TxpSliceList"", { + sl <- TxpSliceList(S1 = TxpSlice(""inpt1""), S2 = TxpSlice(c(""inpt2"", ""inpt3""))) + expect_type(txpValueNames(sl), ""list"") + expect_length(txpValueNames(sl), 2) + expect_type(txpValueNames(sl, simplify = TRUE), ""character"") + expect_length(txpValueNames(sl, simplify = TRUE), 3) + expect_type(txpTransFuncs(sl), ""list"") + expect_length(txpTransFuncs(sl), 2) + expect_s4_class(txpTransFuncs(sl, simplify = TRUE), ""TxpTransFuncList"") + expect_length(txpTransFuncs(sl, simplify = TRUE), 3) +}) + +##----------------------------------------------------------------------------## +## Duplicated + +test_that(""We can detect duplicate TxpSlice objects in TxpSliceList"", { + s1 <- TxpSlice(""inpt1"") + s2 <- TxpSlice(""inpt1"") + s3 <- TxpSlice(""inpt1"", txpTransFuncs = function(x) x^2) + expect_true(any(duplicated(TxpSliceList(s1 = s2, s2 = s2)))) + expect_false(any(duplicated(TxpSliceList(s1 = s1, s3 = s3)))) +}) + +##----------------------------------------------------------------------------## +## Replacement + +test_that(""We can replace TxpSliceList objects"", { + expect_silent({ + s <- TxpSlice(""inpt1"") + l <- TxpSliceList(s1 = s, s2 = s, s3 = s) + }) + expect_s4_class({l[[1]] <- TxpSlice(""hello""); l}, ""TxpSliceList"") + expect_equal(txpValueNames(l[[1]]), ""hello"") + expect_error(l[[2]] <- ""a"") + expect_error(l[2] <- list(NULL)) + expect_error(l[2:3] <- list(TxpSlice(""inpt2""), TxpSlice(""inpt3""))) + expect_s4_class({ + l[2:3] <- list(s4 = TxpSlice(""inpt2""), s5 = TxpSlice(""inpt3"")) + l + }, ""TxpSliceList"") + expect_named(l, c(""s1"", ""s2"", ""s3"")) + expect_equal(txpValueNames(l, simplify = TRUE), + c(s1 = ""hello"", s2 = ""inpt2"", s3 = ""inpt3"")) + expect_named({names(l) <- c(""a"", ""b"", ""c""); l}, c(""a"", ""b"", ""c"")) + expect_named({names(l)[1] <- ""hello""; l}, c(""hello"", ""b"", ""c"")) + expect_named({names(l)[1:2] <- c(""a"", ""hello""); l}, c(""a"", ""hello"", ""c"")) + expect_length({l[2] <- NULL; l}, 2) + expect_equal(txpValueNames(l, simplify = TRUE), c(a = ""hello"", c = ""inpt3"")) +}) +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-txpExportGui.R",".R","2219","85","##----------------------------------------------------------------------------## +## txpExportGui tests +##----------------------------------------------------------------------------## + +test_that(""We can export GUI-ready files"", { + + # Note1 + # Modifying transformation functions in the model causes the ""columns are duplicated"" + # message to be repeated, I'm not sure if that is the desired response + + # Output file for txpExportGui() + data_exported <- tempfile() + # Load data and model + expect_warning({ + gui <- txpImportGui(file.path(""guiFiles"", ""gui_output_data.csv"")) + }) + # No warnings/errors expected for original imported file + expect_silent({ + txpExportGui( + fileName = data_exported, + input = gui$input, + model = gui$model, + id.var = 'Name', + fills = gui$fills + ) + }) + # Non-integer weights + test_model <- gui$model + expect_warning({ + # See Note1 above + txpWeights(test_model)[1] <- 0.5 + }) + expect_error({ + txpExportGui( + fileName = data_exported, + input = gui$input, + model = test_model, + id.var = 'Name', + fills = gui$fills + ) + }) + # Slice-level transformation function + test_model <- gui$model + expect_warning({ + # See Note1 above + txpTransFuncs(test_model)[[1]] <- function(x) log10(x) + }) + expect_warning({ + txpExportGui( + fileName = data_exported, + input = gui$input, + model = test_model, + id.var = 'Name', + fills = gui$fills + ) + }) + # Input-level transformation function that creates negative values + test_model <- gui$model + expect_warning({ + # See Note1 above + txpTransFuncs(txpSlices(test_model)[[1]])[[1]] <- function(x) -x + }) + expect_warning({ + txpExportGui( + fileName = data_exported, + input = gui$input, + model = test_model, + id.var = 'Name', + fills = gui$fills + ) + }) + # Negative input values, expect 3 warnings for the 3 affected slices + test_input <- gui$input + test_input[, 6] <- -test_input[, 6] + expect_warning(expect_warning(expect_warning({ + txpExportGui( + fileName = data_exported, + input = test_input, + model = gui$model, + id.var = 'Name', + fills = gui$fills + ) + }))) +}) +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-txpImportGui.R",".R","1204","28","##----------------------------------------------------------------------------## +## txpImportGui tests +##----------------------------------------------------------------------------## + +test_that(""We can import GUI outputs"", { + expect_warning({ + l <- txpImportGui(file.path(""guiFiles"", ""gui_output_data.csv"")) + }) + expect_type(l, ""list"") + expect_s4_class(l$model, ""TxpModel"") + expect_named(l$model, c(""Slice1"", ""Slice2"", ""Slice3"", ""Slice4"")) + expect_s3_class(l$input, ""data.frame"") + expect_named(l$input, + c(""row"", ""SID"", ""CASRN"", ""Name"", ""metric1"", + ""metric2"", ""metric4"", ""metric3"")) + expect_error(txpImportGui(file.path(""guiFiles"", ""gui_bad_input.csv""))) + expect_error(txpImportGui(file.path(""guiFiles"", + ""gui_output_missingFuncs.csv"")), + ""hitcall\\(x\\), function\\(x\\), f\\(x\\), hello\\(x\\)"") + expect_warning(expect_error({ + txpImportGui(file.path(""guiFiles"", ""gui_output_nonNumeric.csv"")) + }, ""metric1, metric3"")) + # expect_silent({ + # dl <- txpImportGui(file.path(""guiFiles"", ""gui_distributions.csv"")) + # expect_warning(txpCalculateScores(dl$model, dl$input), ""NaNs produced"") + # }) +}) +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpModel.R",".R","5097","124","##----------------------------------------------------------------------------## +## TxpModel tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization + +test_that(""We can create TxpModel objects"", { + expect_silent({ + slcLst <- list(S1 = TxpSlice(""input1""), S2 = TxpSlice(""input2"")) + txpSlcLst <- TxpSliceList(S1 = TxpSlice(""input1""), S2 = TxpSlice(""input2"")) + fxnLst <- list(f1 = function(x) x, f2 = function(x) x^2) + txpFxnLst <- TxpTransFuncList(f1 = function(x) x, f2 = function(x) x^2) + wrnLst <- TxpSliceList(S1 = TxpSlice(""input1""), S2 = TxpSlice(""input1"")) + }) + expect_s4_class(TxpModel(slcLst), ""TxpModel"") + expect_s4_class(TxpModel(txpSlcLst), ""TxpModel"") + expect_s4_class(TxpModel(txpSlices = slcLst, txpTransFuncs = fxnLst), + ""TxpModel"") + expect_s4_class(TxpModel(txpSlices = slcLst, txpTransFuncs = txpFxnLst), + ""TxpModel"") + expect_error(TxpModel(txpSlices = txpSlcLst, txpWeights = 1)) + expect_error(TxpModel(txpSlices = txpSlcLst, txpWeights = ""1"")) + expect_error(TxpModel(txpSlices = txpSlcLst, txpTransFuncs = txpFxnLst[1])) + expect_warning(TxpModel(wrnLst)) +}) + +##----------------------------------------------------------------------------## +## Accessors + +test_that(""TxpModel accessors return expected slots"", { + expect_silent({ + sl <- TxpSliceList(S1 = TxpSlice(""input1""), S2 = TxpSlice(""input2"")) + md <- TxpModel(sl) + }) + expect_s4_class(txpSlices(md), ""TxpSliceList"") + expect_equal(txpWeights(md), rep(1, 2)) + expect_equal(txpWeights(md, adjust = TRUE), rep(0.5, 2)) + expect_s4_class(txpTransFuncs(md), ""TxpTransFuncList"") + expect_equal(txpValueNames(md), list(S1 = ""input1"", S2 = ""input2"")) + expect_equal(txpValueNames(md, simplify = TRUE), + c(S1 = ""input1"", S2 = ""input2"")) + expect_named(md, c(""S1"", ""S2"")) + expect_length(md, 2) +}) + +##----------------------------------------------------------------------------## +## Replace + +test_that(""We can replace TxpModel slots"", { + expect_silent({ + sl1 <- TxpSliceList(S1 = TxpSlice(""input1""), S2 = TxpSlice(""input2"")) + sl2 <- TxpSliceList(S1 = TxpSlice(""input1""), S3 = TxpSlice(""input3"")) + md <- TxpModel(sl1) + fl <- TxpTransFuncList(f1 = function(x) x, f2 = function(x) sqrt(x)) + }) + expect_s4_class(txpSlices(md) <- sl2, ""TxpSliceList"") + expect_named(txpSlices(md), c(""S1"", ""S3"")) + expect_error(txpSlices(md) <- c(""A"", ""B"")) + expect_error(txpSlices(md) <- c(sl1, sl2[2])) + expect_silent(txpWeights(md) <- 1:2) + expect_equal(txpWeights(md), 1:2) + expect_silent(txpTransFuncs(md) <- fl) + expect_named(txpTransFuncs(md), c(""f1"", ""f2"")) + expect_silent(txpTransFuncs(md) <- as.list(fl)[2:1]) + expect_named(txpTransFuncs(md), c(""f2"", ""f1"")) + expect_silent(txpTransFuncs(md) <- NULL) + expect_equal(txpTransFuncs(md), TxpTransFuncList(NULL, NULL)) + md <- TxpModel(c(sl1, sl2[2])) + names(md) <- c(""A"", ""B"", ""C"") + expect_named(md, c(""A"", ""B"", ""C"")) + expect_error(names(md) <- ""hello"") + names(md)[2] <- ""hello"" + expect_named(md, c(""A"", ""hello"", ""C"")) + names(md)[2:3] <- c(""B"", ""hello"") + expect_named(md, c(""A"", ""B"", ""hello"")) +}) + + +##----------------------------------------------------------------------------## +## Show + +test_that(""TxpModel show method displays correct information"", { + mdl <- TxpModel(txpSlices = TxpSliceList(S1 = TxpSlice(""inpt1""), + S2 = TxpSlice(""input2"")), + txpWeights = 1:2, + txpTransFuncs = list(f1 = function(x) x, NULL)) + expect_output(print(mdl), ""txpSlices\\(2\\)"") + expect_output(print(mdl), ""S1 S2"") + expect_output(print(mdl), ""txpWeights\\(2\\)"") + expect_output(print(mdl), ""1 2"") + expect_output(print(mdl), ""txpTransFuncs\\(2\\)"") + expect_output(print(mdl), ""f1 NULL"") +}) + +##----------------------------------------------------------------------------## +## Merge + +test_that(""We can merge two TxpModel objects"", { + expect_silent({ + m1 <- TxpModel(txpSlices = c(S1 = TxpSlice(""inpt1""), + S2 = TxpSlice(""inpt2"")), + txpWeights = 1:2, + txpTransFuncs = list(NULL, linear = function(x) x)) + m2 <- TxpModel(txpSlices = c(S3 = TxpSlice(""inpt3""), + S4 = TxpSlice(""inpt4"")), + txpWeights = 2:1, + txpTransFuncs = list(linear = function(x) x, + sqrt = function(x) sqrt(x))) + m3 <- TxpModel(c(S1 = TxpSlice(""inpt4""))) + m4 <- TxpModel(c(S4 = TxpSlice(""inpt1"")), txpWeights = 3) + }) + expect_s4_class(mrg1 <- merge(m1, m2), ""TxpModel"") + expect_length(mrg1, 4) + expect_named(mrg1, c(""S1"", ""S2"", ""S3"", ""S4"")) + expect_equal(names(txpTransFuncs(mrg1)), c("""", ""linear"", ""linear"", ""sqrt"")) + expect_equal(txpTransFuncs(mrg1)[[4]](100), 10) + expect_equal(txpTransFuncs(mrg1)[[2]](100), 100) + expect_error(txpTransFuncs(mrg1)[[1]](100)) + expect_error(merge(m1, m3)) + expect_warning(merge(m1, m4)) +}) + +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpModelList.R",".R","2496","68","##----------------------------------------------------------------------------## +## TxpModelList tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization + +test_that(""We can create TxpModelList objects"", { + expect_silent(mdl <- TxpModel(TxpSliceList(s1 = TxpSlice(""hello"")))) + expect_s4_class(TxpModelList(mdl, mdl), ""TxpModelList"") + expect_s4_class(TxpModelList(m1 = mdl, m2 = mdl), ""TxpModelList"") + expect_error(TxpModelList(mdl, NULL)) + expect_error(TxpModelList(NULL)) + expect_error(TxpModelList(3)) + expect_length(TxpModelList(mdl, mdl, mdl), 3) + expect_named(TxpModelList(mdl, m = mdl, mdl), c('', 'm', '')) +}) + +##----------------------------------------------------------------------------## +## Show + +test_that(""TxpModelList show method displays correct information"", { + expect_silent({ + mdl <- TxpModel(TxpSliceList(s1 = TxpSlice(""hello""))) + l <- TxpModelList(m1 = mdl, mdl, m3 = mdl) + }) + expect_output(print(l), ""TxpModelList of length 3"") + expect_output(print(l), ""m1 '' m3"") + expect_silent(names(l) <- NULL) + expect_output(print(l), ""'' '' ''"") +}) + +##----------------------------------------------------------------------------## +## Concatenation + +test_that(""We can concatenate TxpModelList objects"", { + expect_silent({ + mdl <- TxpModel(TxpSliceList(s1 = TxpSlice(""hello""))) + l <- TxpModelList(m1 = mdl, mdl, m3 = mdl) + }) + expect_s4_class(cl <- c(l, rev(l), l), ""TxpModelList"") + expect_length(cl, 9) + expect_named(cl, c('m1', '', 'm3', 'm3', '', 'm1', 'm1', '', 'm3')) +}) + +##----------------------------------------------------------------------------## +## Coercion + +test_that(""We can coerce to TxpModelList objects"", { + expect_silent({ + mdl <- TxpModel(TxpSliceList(s1 = TxpSlice(""hello""))) + l <- list(m1 = mdl, mdl, m3 = mdl) + }) + expect_s4_class(as.TxpModelList(l), ""TxpModelList"") + expect_s4_class(as.TxpModelList(l[[1]]), ""TxpModelList"") +}) + +##----------------------------------------------------------------------------## +## Duplicated + +test_that(""We can detect duplicate TxpModel objects in TxpModelList"", { + m1 <- TxpModel(c(S1 = TxpSlice(""inpt1""))) + m2 <- TxpModel(c(S1 = TxpSlice(""inpt1""), S2 = TxpSlice(""inpt2""))) + m3 <- TxpModel(c(S1 = TxpSlice(""inpt1"")), 2) + expect_false(any(duplicated(TxpModelList(m1 = m1, m2 = m2, m3 = m3)))) + expect_true(any(duplicated(TxpModelList(m1 = m1, m2 = m1)))) +}) +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-vsGuiResults.R",".R","4115","143","##----------------------------------------------------------------------------## +## txpExportGui tests +##----------------------------------------------------------------------------## + +test_that(""We reproduce GUI results"", { + + # Get expected results from GUI output + resExpected <- read.csv(file.path(""guiFiles"", ""gui_test_results.csv""), check.names = FALSE) + resExpected <- resExpected[order(resExpected$Name), -c(2:5)] + names(resExpected) <- c('score', sapply(strsplit(names(resExpected)[-1], '!'), '[', 1)) + + ##------------------------------## + # Using txpImportGui + ##------------------------------## + + # Load data and model + expect_warning({ + gui1 <- txpImportGui(file.path(""guiFiles"", ""gui_test_data.csv"")) + }) + + # Compute scores + expect_silent({ + res1 <- txpCalculateScores(gui1$model, gui1$input) + }) + + # Compare ToxPi Scores + expect_equal( + txpScores(res1), + resExpected$score, + ignore_attr = TRUE + ) + + # Compare Slice Scores + expect_equal( + as.data.frame(txpSliceScores(res1, adjusted = FALSE)), + resExpected[,-1], + ignore_attr = TRUE + ) + + ##------------------------------## + # Using output from txpExportGui + ##------------------------------## + + # Export model, suppress expected warnings about containing negative values + data_exported <- tempfile() + expect_silent({ + suppressWarnings( + txpExportGui( + fileName = data_exported, + input = gui1$input, + model = gui1$model, + id.var = 'Name', + fills = gui1$fills + ) + ) + }) + + # Load data and model + expect_silent({ + gui2 <- txpImportGui(data_exported) + }) + + # Compute scores + expect_silent({ + res2 <- txpCalculateScores(gui2$model, gui2$input) + }) + + # Compare ToxPi Scores + expect_equal( + txpScores(res2), + resExpected$score, + ignore_attr = TRUE + ) + + # Compare Slice Scores + expect_equal( + as.data.frame(txpSliceScores(res2, adjusted = FALSE)), + resExpected[,-1], + ignore_attr = TRUE + ) + + ##------------------------------## + # Manually created model + ##------------------------------## + + # Create model + input <- read.csv(file.path(""guiFiles"", ""gui_test_data.csv""), skip = 40, check.names = FALSE, stringsAsFactors = FALSE) + + slices <- TxpSliceList() + nFn <- 10 + for ( i in 1:nFn ) { + fn <- switch( + i, + function(x) x, # 1: linear(x) + function(x) as.integer(x != 0), # 2: hit count + function(x) ifelse(x <= 0, NA, -log10(x)), # 3: -log10(x) + function(x) ifelse(x <= 0, NA, -log10(x) + log10(max(x, na.rm = TRUE))), # 4: -log10(x)+log10(max(x)) + function(x) ifelse(x <= 0, NA, -log10(x) + 6), # 5: -log10(x)+6 + function(x) ifelse(x <= 0, NA, -log(x)), # 6: -ln(x) + function(x) ifelse(x <= 0, NA, log10(x)), # 7: log10(x) + function(x) sqrt(x), # 8: sqrt(x) + function(x) (x - mean(x, na.rm = TRUE))/sd(x, na.rm = TRUE), # 9: zscore(x) + function(x) (x - min(x, na.rm = TRUE))/diff(range(x, na.rm = TRUE)), # 10: uniform(x) + function(x) x # default + ) + addSlices <- TxpSliceList( + b = TxpSlice(c(""y1a"", ""y1b""), TxpTransFuncList(fn, fn)), + a = TxpSlice(""y1a"", TxpTransFuncList(fn)), + d = TxpSlice(c(""y2a"", ""y2b""), TxpTransFuncList(fn, fn)), + c = TxpSlice(""y2a"", TxpTransFuncList(fn)) + ) + names(addSlices) <- paste0('Slice', i, c('_1ab', '_1a', '_2ab', '_2a')) + slices <- c(slices, addSlices) + } + + expect_warning({ + model <- TxpModel( + txpSlices = slices, + txpWeights = rep(c(2,1,2,1), nFn) + ) + }) + + # Compute scores + expect_silent({ + res3 <- txpCalculateScores(model, input, negative.value.handling = 'missing') + }) + + # Compare ToxPi Scores + expect_equal( + txpScores(res3), + resExpected$score, + ignore_attr = TRUE + ) + + # Compare Slice Scores + expect_equal( + as.data.frame(txpSliceScores(res3, adjusted = FALSE)), + resExpected[,-1], + ignore_attr = TRUE + ) + +}) +","R" +"Toxicology","ToxPi/toxpiR","tests/testthat/test-TxpTransFunc.R",".R","956","26","##----------------------------------------------------------------------------## +## TxpTransFunc tests +##----------------------------------------------------------------------------## + +##----------------------------------------------------------------------------## +## Initialization + +test_that(""We can create TxpTransFunc objects"", { + fx <- function(x) x + 1 + expect_s4_class(tf <- TxpTransFunc(fx), ""TxpTransFunc"") + expect_s4_class(as(fx, ""TxpTransFunc""), ""TxpTransFunc"") + expect_condition(body(tf) == ""x + 1"", regexp = NA) + expect_equal(formalArgs(tf), ""x"") + expect_equal(tf(1:10), 1:10 + 1) + expect_error(TxpTransFunc(function(x) ""hello"")) + expect_error(TxpTransFunc(function(x) x + ""a"")) + expect_error(TxpTransFunc(1)) +}) + +test_that(""TxpTransFunc can handle primitives"", { + expect_warning(f1 <- TxpTransFunc(sqrt)) + expect_equal(f1(1:10), sqrt(1:10)) + expect_warning(f2 <- as(sqrt, ""TxpTransFunc"")) + expect_equal(f2(1:10), sqrt(1:10)) +}) +","R" +"Toxicology","pfnet-research/hierarchical-molecular-learning","unsupNFP/train.py",".py","2734","92","import argparse + +from chainer import optimizers +from chainer import serializers +import numpy as np + +import model +import load_mutag +import load_nci1 +import classification + + +n_epoch = 200 +n_parts = 5 + +parser = argparse.ArgumentParser() +parser.add_argument('dataset', type=str, choices=('mutag', 'ptc')) +args = parser.parse_args() + +if args.dataset == 'mutag': + mutag_file_name = ""MUTAG.mat"" + graphs = load_mutag.load_whole_data('MUTAG.mat') + MAX_EDGE_TYPE = load_mutag.MAX_EDGE_TYPE + MAX_NUMBER_ATOM = load_mutag.MAX_NUMBER_ATOM +elif args.dataset == 'ptc': + smile_filename = 'corrected_smiles.txt' + result_filename = 'corrected_results.txt' + graphs = load_nci1.load_ptc(smile_filename, result_filename) + MAX_EDGE_TYPE = load_nci1.MAX_EDGE_TYPE + MAX_NUMBER_ATOM = load_nci1.MAX_NUMBER_ATOM +else: + raise ValueError('Invalid dataset type: {}'.format(args.dataset)) + +model.MAX_EDGE_TYPE = MAX_EDGE_TYPE +model.MAX_NUMBER_ATOM = MAX_NUMBER_ATOM + +indexs_test = np.random.permutation(len(graphs)) +n_graphs = len(graphs) +print(""num of graphs:"", n_graphs) + + +rep_dim = 101 +max_degree = 5 +num_levels = 6 +neg_size = 10 +batchsize = 100 + +hid_dim = 100 +out_dim = 2 + +softmax = model.SoftmaxCrossEntropy(rep_dim, MAX_NUMBER_ATOM) +print(""[CONFIG: representation dim ="", rep_dim, ""]"") +atom2vec = model.Atom2vec(MAX_NUMBER_ATOM, rep_dim, max_degree, softmax) +model = model.Mol2Vec(len(graphs), rep_dim, max_degree, + num_levels, neg_size, atom2vec) + +optimizer = optimizers.Adam() +optimizer.setup(model) +print(""start training"") +for epoch in range(1, n_epoch + 1): + print(""epoch:"", epoch) + indexes = np.random.permutation(len(graphs)) + sum_loss = 0 + + for i in range(0, n_graphs, batchsize): + maxid = min(i + batchsize, n_graphs) + ids = indexes[i:maxid] + + graphids = [] + adjs = [] + atom_arrays = [] + for id in indexes[i:maxid]: + graphids.append(graphs[id][0]) + # index 1 and 2 need to be changed for MUTAG or NCI1 datasets + atom_arrays.append(graphs[id][1]) + adjs.append(graphs[id][2]) + + graphids = np.asarray(graphids) + adjs = np.asarray(adjs, dtype=np.float32) + atom_arrays = np.asarray(atom_arrays, dtype=np.int32) + optimizer.update(model, graphids, adjs, atom_arrays) + + sum_loss += float(model.loss.data) * len(graphids) + print(""-----"", float(model.loss.data) * len(graphids)) + print(""loss: "", sum_loss / n_graphs) + serializers.save_npz(str(rep_dim) + ""_model_ptc.npz"", model) + + # after each epcoh, check result + if epoch % 10 == 0: + classification.MLPClassifier(model, graphs, indexs_test, + rep_dim, batchsize) +","Python" +"Toxicology","pfnet-research/hierarchical-molecular-learning","unsupNFP/load_nci1.py",".py","5745","205","import numpy as np +from rdkit.Chem import MolFromSmiles +from scipy.io import loadmat + + +MAX_EDGE_TYPE = 4 +MAX_NUMBER_ATOM = 120 + + +def construct_edge_matrix_from(mol): + if mol is None: + return None + N = mol.GetNumAtoms() + size = MAX_NUMBER_ATOM + adjs = np.zeros((4, size, size), dtype=np.float32) + for i in range(N): + for j in range(N): + bond = mol.GetBondBetweenAtoms(i, j) # type: Chem.Bond + if bond is not None: + bondType = str(bond.GetBondType()) + if bondType == 'SINGLE': + adjs[0, i, j] = 1.0 + elif bondType == 'DOUBLE': + adjs[1, i, j] = 1.0 + elif bondType == 'TRIPLE': + adjs[2, i, j] = 1.0 + elif bondType == 'AROMATIC': + adjs[3, i, j] = 1.0 + else: + print(""[ERROR] Unknown bond type"", bondType) + assert False # Should not come here + return adjs + + +def getAtom2id(graphs): + max_atom = 0 + for graph in graphs: + atom_list = graph[1] + max_atom = max(max_atom, len(atom_list)) + assert max_atom <= MAX_NUMBER_ATOM + atom2id = {'empty': 0} + atoms = [graph[1] for graph in graphs] + atoms = sum(atoms, []) + for a in atoms: + if a not in atom2id: + atom2id[a] = len(atom2id) + print(atom2id) + return atom2id + + +def load_nci1_file(filename): + """""" + + :param filename: + :return: list of graph, each consists of graphID, + list of atoms, list of edges + + """""" + inputdata = loadmat(filename) + data = inputdata['NCI1'] + labels = inputdata['lnci1'].tolist() + atom_lists = data[""nl""][0] + edge_lists = data[""el""][0] + adj_lists = data[""al""][0] + + size = len(atom_lists) + graphs = [] + for i in range(size): + graphId = i + tmp = atom_lists[graphId][0][0][0] + atom_list = [a[0] for a in tmp] + tmp = edge_lists[graphId][0][0][0] + edge_list = [] + for e in tmp: + e_l = e[0].tolist() + edge_list.append(e_l) + + tmp = adj_lists[graphId] + adj_list = [a[0].tolist() for a in tmp] + label = labels[graphId][0] + graphs.append((graphId, atom_list, adj_list, edge_list, label)) + return graphs + + +def convert_graph(graphs): + n_graphs = len(graphs) + edge2id = {'empty': 0} + all_edges = [] + for graph in graphs: + edge_list = graph[2] + for edge in edge_list: + all_edges.append(edge) + all_edges = sum(all_edges, []) + print(all_edges) + + for i in range(n_graphs): + for j in range(len(graphs[i][2])): + edge_id = graphs[i][2][j][2] + graphs[i][2][j][2] = edge2id[str(edge_id)] + print(""MAX NUMBER of EDGES"", len(edge2id)) + return graphs, edge2id + + +def construct_edge_matrix(graph): + atom_list = graph[1] + adj_list = graph[2] + edge_list = graph[3] + + N = len(atom_list) # number of atoms in the molecule + size = MAX_NUMBER_ATOM + adjs = np.zeros((MAX_EDGE_TYPE, size, size), dtype=np.float32) + + for i in range(N): + node1 = i + adj_atoms = adj_list[i] # [4,5,6] + if len(adj_atoms) == 0: + continue + edge_labels = edge_list[i] # [1,1,2] + n_adj = len(adj_atoms) + for j in range(n_adj): + node2 = adj_atoms[0][j] + edge_type = edge_labels[0][j] + adjs[edge_type - 1, node1, node2] = 1.0 + return adjs + + +def load_whole_data(filename): + results = [] + graphs = load_nci1_file(filename) + for graph in graphs: + graphid = graph[0] + atom_array = np.zeros((MAX_NUMBER_ATOM,), dtype=np.int32) + atom_list = graph[1] + natoms = len(atom_list) + atom_array[:natoms] = np.array(atom_list) + label = graph[4] + adjs = construct_edge_matrix(graph) + results.append((graphid, atom_array, adjs, label)) + return results + + +def check_graph(graph): + print(""graphID:"", graph[0]) + print(""atom list:"", graph[1]) + print(""adj :"", graph[2][1][1]) + print(""label:"", graph[3]) + print('size of atom list:', len(graph[1])) + + +def convert_graph_1(graphs, atom2id): + ret = [] + for graph in graphs: + (id, atom_list, adj, label) = graph + atom_list = [atom2id[a] for a in atom_list] + n_atom = len(atom_list) + atom_array = np.zeros((MAX_NUMBER_ATOM,), dtype=np.int32) + atom_array[:n_atom] = np.array(atom_list) + + ret.append((id, atom_array, adj, label)) + return ret + + +def load_ptc(smile_file, result_file): + filtered = [] + valid_list = ['MR=P', 'MR=CE', 'MR=SE', 'MR=NE', 'MR=N'] + f_smile = open(smile_file, 'r') + f_result = open(result_file, 'r') + smiles = [] + labels = [] + for line in f_smile: + smile = line.split()[1] + smiles.append(smile) + for line in f_result: + words = line.split(',') + data = words[0] + label = data.split()[1] + labels.append(label) + + for i in range(len(smiles)): + smile = smiles[i] + label = labels[i] + if label not in valid_list: + continue + if label in ['MR=P', 'MR=CE', 'MR=SE']: + label = 1 + else: + label = 0 + filtered.append((smile, label)) + + graphs = [] + id = 0 + for data in filtered: + smile = data[0] + label = data[1] + mol = MolFromSmiles(str(smile)) + if mol is None: + continue + adj = construct_edge_matrix_from(mol) + atom_list = [a.GetSymbol() for a in mol.GetAtoms()] + graphs.append((id, atom_list, adj, label)) + id += 1 + atom2id = getAtom2id(graphs) + graphs = convert_graph_1(graphs, atom2id) + return graphs +","Python" +"Toxicology","pfnet-research/hierarchical-molecular-learning","unsupNFP/classification.py",".py","2890","84","import model +import chainer +from chainer import serializers +import numpy as np + + +def MLPClassifier(unsmodel, graphs, indexes, rep_dim, batchsize): + print('start classification') + split = int(len(indexes) * 0.9) + graph_train = [] + graph_test = [] + + for i in indexes[0:split]: + graph_train.append(graphs[i]) + + for i in indexes[split:len(indexes)]: + graph_test.append(graphs[i]) + + serializers.load_npz(str(rep_dim) + ""_model_ptc.npz"", unsmodel) + + hid_dim = 150 + out_dim = 2 + mlp = model.MLP(rep_dim, hid_dim, out_dim) + classifier = model.SoftmaxClassifier(mlp) + optimizer = chainer.optimizers.Adam() + optimizer.setup(classifier) + n_epochs = 30 + + # training phase + best = 0.00 + for epoch in range(n_epochs): + print(""epoch:"", epoch) + perm = np.random.permutation(len(graph_train)) + N_train = len(graph_train) + sum_loss = 0 + sum_accuracy = 0 + for i in range(0, N_train, batchsize): + maxid = min(i + batchsize, N_train) + graphids = [] + adjs = [] + atom_arrays = [] + labels = [] + for id in perm[i:maxid]: + graphids.append(graph_train[id][0]) + adjs.append(graph_train[id][2]) + atom_arrays.append(graph_train[id][1]) + labels.append(graph_train[id][3]) + graphids = np.asarray(graphids) + adjs = np.asarray(adjs, dtype=np.float32) + atom_arrays = np.asarray(atom_arrays, dtype=np.int32) + labels = np.asarray(labels, dtype=np.int32) + rep_list, counts = unsmodel.extract_fp(graphids, adjs, atom_arrays) + y = chainer.Variable(labels) + x = rep_list + optimizer.update(classifier, x, counts, y) + sum_loss += float(classifier.loss.data) * len(y.data) + sum_accuracy += float(classifier.accuracy.data) * len(y.data) + print(""train acc:"", sum_accuracy / N_train, + ""train loss:"", sum_loss / N_train) + if best < sum_accuracy: + serializers.save_npz(str(rep_dim) + ""_nn_ptc.npz"", classifier) + best = sum_accuracy + + # test + graphids = [] + adjs = [] + atom_arrays = [] + labels = [] + serializers.load_npz(str(rep_dim) + ""_nn_ptc.npz"", classifier) + for id in range(len(graph_test)): + graphids.append(graph_test[id][0]) + adjs.append(graph_test[id][2]) + atom_arrays.append(graph_test[id][1]) + labels.append(graph_test[id][3]) + graphids = np.asarray(graphids) + adjs = np.asarray(adjs, dtype=np.float32) + atom_arrays = np.asarray(atom_arrays, dtype=np.int32) + labels = np.asarray(labels, dtype=np.int32) + rep_list, counts = unsmodel.extract_fp(graphids, adjs, atom_arrays) + + x = rep_list + y = chainer.Variable(labels) + print(""test acc:"", classifier.accuracy.data) +","Python" +"Toxicology","pfnet-research/hierarchical-molecular-learning","unsupNFP/model.py",".py","14930","404","import chainer +import chainer.functions as F +import chainer.links as L +from chainer import ChainList +import numpy as np +import six + + +global MAX_EDGE_TYPE +global MAX_NUMBER_ATOM +MAX_EDGE_TYPE = None +MAX_NUMBER_ATOM = None +# max atom type for NCI1 must be large +MAX_ATOM_TYPE = 50 + + +class SoftmaxCrossEntropy(chainer.Chain): + def __init__(self, n_in, n_out): + super(SoftmaxCrossEntropy, self).__init__() + with self.init_scope(): + self.out = L.Linear(n_in, n_out, initialW=0) + + def __call__(self, x, t): + return F.softmax_cross_entropy(self.out(x), t) + + +class Atom2vec(chainer.Chain): + def __init__(self, n_atoms, rep_dim, max_degree, loss_func): + super(Atom2vec, self).__init__() + num_degree_type = max_degree + 1 + with self.init_scope(): + self.atom_embed = L.EmbedID(n_atoms, rep_dim) + self.hidden_weights = chainer.ChainList( + *[L.Linear(rep_dim, rep_dim) + for _ in range(num_degree_type)] + ) + self.edge_layer = L.Linear(rep_dim, MAX_EDGE_TYPE * rep_dim) + self.loss_func = loss_func + self.max_degree = num_degree_type + self.rep_dim = rep_dim + + def __call__(self, adj, atom_array): + counts = [] + for list_atom in atom_array: + list_atom = np.array(list_atom) + count = np.count_nonzero(list_atom) + counts.append(count) + x = self.atom_embed(atom_array) + degree_mat = F.sum(adj, axis=1) + degree_mat = F.sum(degree_mat, axis=1) + + s0, s1, s2 = x.shape + m = F.reshape(self.edge_layer(F.reshape(x, (s0 * s1, s2))), + (s0, s1, s2, MAX_EDGE_TYPE)) + m = F.transpose(m, (0, 3, 1, 2)) + adj = F.reshape(adj, (s0 * MAX_EDGE_TYPE, s1, s1)) + m = F.reshape(m, (s0 * MAX_EDGE_TYPE, s1, s2)) + m = F.batch_matmul(adj, m) + m = F.reshape(m, (s0, MAX_EDGE_TYPE, s1, s2)) + m = F.sum(m, axis=1) + s0, s1, s2 = m.shape + m = F.reshape(m, (s0 * s1, s2)) + + atom_array = np.asarray(atom_array).reshape(-1) + for s_index in range(s0): + atom_array[counts[s_index] + s_index * s1:(s_index + 1) * s1] = -1 + + t = chainer.Variable(atom_array) + self.loss = self.loss_func(m, t) + return self.loss + + +class MLP(chainer.Chain): + def __init__(self, n_in, n_hid, n_out): + super(MLP, self).__init__() + with self.init_scope(): + self.softmax = L.Linear(None, n_hid) + self.l1 = L.Linear(None, n_hid) + self.l2 = L.Linear(None, n_hid) + self.l3 = L.Linear(None, n_out) + self.n_in = n_in + self.n_hid = n_hid + self.n_out = n_out + + def __call__(self, x_list, counts): + h = 0 + for x in x_list: + s0, s1, s2 = x.shape + x = F.reshape(x, (s0 * s1, s2)) + dh = self.softmax(x) + dh = F.softmax(dh) + for s_index in range(s0): + _from = counts[s_index] + s_index * s1 + _to = (s_index + 1) * s1 + dh.data[_from:_to, :] = 0.0 + dh = F.sum(F.reshape(dh, (s0, s1, self.n_hid)), axis=1) + h += dh + # got h + h = F.relu(self.l1(h)) + y = self.l3(h) + return y + + +class SoftmaxClassifier(chainer.Chain): + def __init__(self, predictor): + super(SoftmaxClassifier, self).__init__(predictor=predictor) + + def __call__(self, x, counts, t, test=False): + y = self.predictor(x, counts) + self.loss = F.softmax_cross_entropy(y, t) + self.accuracy = F.accuracy(y, t) + return self.loss + + +class Mol2Vec2(chainer.Chain): + def __init__(self, num_molecules, rep_dim, max_degree, num_levels): + super(Mol2Vec2, self).__init__() + num_degree_type = max_degree + 1 + with self.init_scope(): + self.mol_embed_layer = L.EmbedID(num_molecules, rep_dim) + self.atom_embed_layer = L.EmbedID(MAX_NUMBER_ATOM, rep_dim) + self.edge_layer = L.Linear(rep_dim, rep_dim * MAX_EDGE_TYPE) + self.out = L.Linear(rep_dim, MAX_ATOM_TYPE) + self.H = ChainList(*[ChainList( + *[L.Linear(rep_dim, rep_dim) + for i in six.moves.range(num_degree_type)]) + for j in six.moves.range(num_levels)]) + # representation dim of molecules, substructures and atoms + self.rep_dim = rep_dim + self.max_degree_type = num_degree_type + self.num_mol = num_molecules + self.n_levels = num_levels + + def one_step(self, mol_reps, sub_reps, adj, atom_array, counts): + s0, s1, s2 = sub_reps.shape + tmp = self.edge_layer(F.reshape(sub_reps, (s0 * s1, s2))) + m = F.reshape(tmp, (s0, s1, s2, MAX_EDGE_TYPE)) + m = F.transpose(m, (0, 3, 1, 2)) + m = F.reshape(m, (s0 * MAX_EDGE_TYPE, s1, s2)) + adj = F.reshape(adj, (s0 * MAX_EDGE_TYPE, s1, s1)) + m = F.batch_matmul(adj, m) + m = F.reshape(m, (s0, MAX_EDGE_TYPE, s1, s2)) + m = F.sum(m, axis=1) + s0, s1, s2 = m.shape + m = F.reshape(m, (s0 * s1, s2)) + mol_reps = F.tile(mol_reps, (1, s1)) + mol_reps = F.reshape(mol_reps, (s0 * s1, s2)) + reps = mol_reps + m + atom_array = atom_array.flatten() + for s_index in range(s0): + _from = counts[s_index] + s_index * s1 + _to = (s_index + 1) * s1 + reps.data[_from:_to, :] = 0.0 + atom_array[_from:_to] = -1 + + t = chainer.Variable(atom_array) + loss = F.softmax_cross_entropy(self.out(reps), t) + return loss + + def message_and_update(self, cur, adj, deg_conds, counts, level): + + s0, s1, s2 = cur.shape + tmp = self.edge_layer(F.reshape(cur, (s0 * s1, s2))) + m = F.reshape(tmp, (s0, s1, s2, MAX_EDGE_TYPE)) + m = F.transpose(m, (0, 3, 1, 2)) + m = F.reshape(m, (s0 * MAX_EDGE_TYPE, s1, s2)) + adj = F.reshape(adj, (s0 * MAX_EDGE_TYPE, s1, s1)) + m = F.batch_matmul(adj, m) + + m = F.reshape(m, (s0, MAX_EDGE_TYPE, s1, s2)) + m = F.sum(m, axis=1) + m = m + cur + s0, s1, s2 = m.shape + zero_array = np.zeros(m.shape, dtype=np.float32) + ms = [F.reshape(F.where(cond, m, zero_array), (s0 * s1, s2)) + for cond in deg_conds] + out_x = 0 + for hidden_weight, m in zip(self.H[level], ms): + out_x = out_x + hidden_weight(m) + out_x = F.sigmoid(out_x) + for s_index in range(s0): + _from = counts[s_index] + s_index * s1 + _to = (s_index + 1) * s1 + out_x.data[_from:_to, :] = 0.0 + + out_x = F.reshape(out_x, (s0, s1, s2)) + return out_x + + def __call__(self, ids, adj, atom_array): + ids = np.array(ids, dtype=np.int32) + counts = [] + for list_atom in atom_array: + list_atom = np.array(list_atom) + count = np.count_nonzero(list_atom) + counts.append(count) + + mol_rep = self.mol_embed_layer(ids) + sub_rep = self.atom_embed_layer(atom_array) + degree_mat = F.sum(adj, axis=1) + degree_mat = F.sum(degree_mat, axis=1) + deg_conds = [np.broadcast_to( + ((degree_mat - degree).data == 0)[:, :, None], + sub_rep.shape) + for degree in range(1, self.max_degree_type + 1)] + + self.loss = 0 + for level in range(self.n_levels): + loss = self.one_step(mol_rep, sub_rep, adj, atom_array, counts) + sub_rep = self.message_and_update( + sub_rep, adj, deg_conds, counts, level) + self.loss += loss + return self.loss + + +class Mol2Vec(chainer.Chain): + def __init__(self, num_molecules, rep_dim, max_degree, + num_levels, neg_size, atom2vec): + super(Mol2Vec, self).__init__() + num_degree_type = max_degree + 1 + with self.init_scope(): + self.gate_weight = L.Linear(rep_dim, 1) + self.mol_embed_layer = L.EmbedID(num_molecules, rep_dim) + self.atom_embed_layer = L.EmbedID(MAX_ATOM_TYPE, rep_dim) + self.edge_layer = L.Linear(rep_dim, rep_dim * MAX_EDGE_TYPE) + self.H = ChainList(*[ChainList( + *[L.Linear(rep_dim, rep_dim) + for i in six.moves.range(num_degree_type)]) + for j in six.moves.range(num_levels)]) + # representation dim of molecules, substructures and atoms + self.rep_dim = rep_dim + self.max_degree_type = num_degree_type + self.num_mol = num_molecules + self.neg_size = neg_size + self.n_levels = num_levels + self.atom2vec = atom2vec + + def extract_fp(self, ids, adj, atom_array): + counts = [] + for list_atom in atom_array: + list_atom = np.array(list_atom) + count = np.count_nonzero(list_atom) + counts.append(count) + + out = [] + sub_rep = self.atom_embed_layer(atom_array) + out.append(sub_rep) + + degree_mat = F.sum(adj, axis=1) + degree_mat = F.sum(degree_mat, axis=1) + deg_conds = [np.broadcast_to( + ((degree_mat - degree).data == 0)[:, :, None], + sub_rep.shape) + for degree in range(1, self.max_degree_type + 1)] + for level in range(self.n_levels): + sub_rep = self.message_and_update( + sub_rep, adj, deg_conds, counts, level) + out.append(sub_rep) + return out, counts + + def message_and_update(self, cur, adj, deg_conds, counts, level): + + s0, s1, s2 = cur.shape + tmp = self.edge_layer(F.reshape(cur, (s0 * s1, s2))) + + m = F.reshape(tmp, (s0, s1, s2, MAX_EDGE_TYPE)) + m = F.transpose(m, (0, 3, 1, 2)) + m = F.reshape(m, (s0 * MAX_EDGE_TYPE, s1, s2)) + + adj = F.reshape(adj, (s0 * MAX_EDGE_TYPE, s1, s1)) + + m = F.batch_matmul(adj, m) + m = F.reshape(m, (s0, MAX_EDGE_TYPE, s1, s2)) + m = F.sum(m, axis=1) + m = m + cur + s0, s1, s2 = m.shape + zero_array = np.zeros(m.shape, dtype=np.float32) + ms = [F.reshape(F.where(cond, m, zero_array), (s0 * s1, s2)) + for cond in deg_conds] + out_x = 0 + for hidden_weight, m in zip(self.H[level], ms): + out_x = out_x + hidden_weight(m) + out_x = F.sigmoid(out_x) + for s_index in range(s0): + _from = counts[s_index] + s_index * s1 + _to = (s_index + 1) * s1 + out_x.data[_from:_to:, :] = 0.0 + + out_x = F.reshape(out_x, (s0, s1, s2)) + return out_x + + def __call__(self, ids, adj, atom_array): + ids = np.array(ids, dtype=np.int32) + counts = [] + for list_atom in atom_array: + list_atom = np.array(list_atom) + count = np.count_nonzero(list_atom) + counts.append(count) + + mol_rep = self.mol_embed_layer(ids) + sub_rep = self.atom_embed_layer(atom_array) + + degree_mat = F.sum(adj, axis=1) + degree_mat = F.sum(degree_mat, axis=1) + deg_conds = [np.broadcast_to( + ((degree_mat - degree).data == 0)[:, :, None], + sub_rep.shape) + for degree in range(1, self.max_degree_type + 1)] + + self.loss = 0 + self.pos = 0 + self.neg = 0 + for level in range(self.n_levels): + sub_rep = self.message_and_update( + sub_rep, adj, deg_conds, counts, level) + neg_rep = self.sampler(sub_rep, self.neg_size, counts) + loss = self.loss_func(mol_rep, sub_rep, neg_rep, counts, level) + + self.loss += loss + return self.loss + + def loss_func(self, mol_rep, pos, neg, counts, level): + s0, s1, s2 = pos.shape + assert s0 == mol_rep.shape[0] + assert s2 == mol_rep.shape[1] + + # molecules + mol_rep = F.tile(mol_rep, (1, s1)) + mol_rep = F.reshape(mol_rep, (s0 * s1, s2)) + + # poss part + pos = F.reshape(pos, (s0 * s1, s2)) + gate = F.exp((self.gate_weight(pos))) + norm = gate + norm = F.reshape(norm, (s0, s1)) + norm = F.sum(norm, axis=1) + norm_rep = F.reshape(F.tile(norm, (1, s1)), (s0 * s1, 1)) + gate = gate / norm_rep + + pos_loss = F.sum(mol_rep * pos, axis=1) + pos_loss = F.reshape(pos_loss, (s0 * s1, 1)) + + mol_rep_re = F.tile(mol_rep, (1, self.neg_size)) + mol_rep_re = F.reshape(mol_rep_re, (s0 * s1 * self.neg_size, s2)) + neg = F.reshape(neg, (s0 * s1 * self.neg_size, s2)) + neg_loss = F.sum(-mol_rep_re * neg, axis=1) + neg_loss = F.reshape(neg_loss, (s0 * s1, self.neg_size)) + + pos_t = [1 for _ in range(s0 * s1)] + for s_index in range(s0): + _from = counts[s_index] + s_index * s1 + _to = (s_index + 1) * s1 + pos_t[_from:_to] = [-1 for aa in pos_t[_from:_to]] + pos_t = chainer.Variable(np.array(pos_t, dtype=np.int32)) + pos_t = F.reshape(pos_t, (s0 * s1, 1)) + pos = F.sigmoid_cross_entropy(pos_loss, pos_t, reduce=""no"") + pos = F.sum(pos) + + neg = F.sigmoid_cross_entropy( + neg_loss, F.tile(pos_t, (1, self.neg_size)), reduce=""no"") + neg = F.sum(neg) + self.pos += pos + self.neg += neg + return pos + neg / self.neg_size + + def check_present(self, sub_list, sub): + for _sub in sub_list: + if np.sum(sub - _sub) == 0: + return True + return False + + def sampler(self, sub_rep, negSampSize, counts): + s0, s1, s2 = sub_rep.shape + sub_rep = F.reshape(sub_rep, (s0 * s1, s2)) + + sub_rep_arr = sub_rep.data + negatives = [] + + for sam_index in range(s0): + for atom_index in range(counts[sam_index]): + n_neg_sample = 0 + neg_samps = None + + while n_neg_sample < negSampSize: + rand_sam = np.random.random_integers(0, s0 - 1) + rand_atom = np.random.random_integers( + 0, counts[rand_sam] - 1) + row_index = s1 * rand_sam + rand_atom + neg_samp = sub_rep_arr[row_index, :] + + _from = sam_index * s1 + _to = sam_index * s1 + counts[sam_index] + if self.check_present(sub_rep_arr[_from:_to, :], neg_samp): + continue + if n_neg_sample == 0: + neg_samps = neg_samp + else: + neg_samps = np.concatenate((neg_samps, neg_samp)) + n_neg_sample += 1 + negatives.append(neg_samps) + for atom_index in range(counts[sam_index], s1): + neg_samples = np.zeros(s2 * negSampSize, dtype=np.float32) + negatives.append(neg_samples) + return chainer.Variable(np.asarray(negatives)) +","Python" +"Toxicology","pfnet-research/hierarchical-molecular-learning","unsupNFP/load_mutag.py",".py","2428","94","from scipy.io import loadmat +import numpy as np + + +MAX_EDGE_TYPE = 12 +MAX_NUMBER_ATOM = 120 + + +def load_mutag_file(filename): + """""" + + :param filename: + :return: list of graph, each consists of graphID, + list of atoms, list of edges + + """""" + inputdata = loadmat(""MUTAG.mat"") + data = inputdata[""MUTAG""] + labels = inputdata[""lmutag""].tolist() + atom_lists = data[""nl""][0] + edge_lists = data[""el""][0] + + size = len(atom_lists) + graphs = [] + for i in range(size): + graphId = i + tmp = atom_lists[i][0][0][0] + atom_list = [a[0] for a in tmp] + tmp = edge_lists[i][0][0][0] + edge_list = [e.tolist() for e in tmp] + label = labels[i][0] + if label == 1: + label = 1 + else: + label = 0 + graphs.append((graphId, atom_list, edge_list, label)) + return graphs + + +def convert_graph(graphs): + n_graphs = len(graphs) + edge2id = {'empty': 0} + for graph in graphs: + edge_list = graph[2] + for edge in edge_list: + edge_id = str(edge[2]) + if edge_id not in edge2id: + edge2id[edge_id] = len(edge2id) + + for i in range(n_graphs): + for j in range(len(graphs[i][2])): + edge_id = graphs[i][2][j][2] + graphs[i][2][j][2] = edge2id[str(edge_id)] + print(""MAX NUMBER of EDGES"", len(edge2id)) + return graphs, edge2id + + +def construct_edge_matrix(graph): + edge_list = graph[2] + + size = MAX_NUMBER_ATOM + adjs = np.zeros((MAX_EDGE_TYPE, size, size), dtype=np.float32) + + for edge in edge_list: + node1 = edge[0] + node2 = edge[1] + edge_type = edge[2] + adjs[edge_type, node1, node2] = 1.0 + adjs[edge_type, node2, node1] = 1.0 + return adjs + + +def load_whole_data(filename): + results = [] + graphs = load_mutag_file(filename) + graphs, edge2id = convert_graph(graphs) + for graph in graphs: + graphid = graph[0] + atom_array = np.zeros((MAX_NUMBER_ATOM,), dtype=np.int32) + atom_list = graph[1] + natoms = len(atom_list) + atom_array[:natoms] = np.array(atom_list) + label = graph[3] + adjs = construct_edge_matrix(graph) + results.append((graphid, atom_array, adjs, label)) + return results + + +def check_graph(graph): + print(""graphID:"", graph[0]) + print(""atom list:"", graph[1]) + print(""adjs:"", graph[2]) + print(""label:"", graph[3]) +","Python"