diff --git a/.Rbuildignore b/.Rbuildignore index 0a52d3b..725e18f 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -19,3 +19,4 @@ index.md ^CRAN-SUBMISSION$ ^cran-comments\.md$ ^vignettes/(?!overview.Rmd) +^LICENSE\.md$ diff --git a/DESCRIPTION b/DESCRIPTION index 585582e..0129313 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: samc Type: Package Title: Spatial Absorbing Markov Chains -Version: 3.2.1 +Version: 3.3.0 Authors@R: c( person("Andrew", "Marx", , "ajm.rpackages@gmail.com", role = c("aut", "cre", "cph"), comment = c(ORCID = "0000-0002-7456-1631") @@ -32,7 +32,7 @@ Description: Implements functions for working with absorbing Markov chains. The short-term and long-term predictions for metrics related to connectivity in landscapes. Despite the ecological context of the framework, this package can be used in any application of absorbing Markov chains. -License: GPL (>=3) +License: AGPL (>= 3) URL: https://andrewmarx.github.io/samc/ BugReports: https://github.com/andrewmarx/samc/issues/ Encoding: UTF-8 @@ -44,7 +44,7 @@ Imports: raster, terra (>= 1.7-3), circular -RoxygenNote: 7.2.3 +RoxygenNote: 7.3.2 Suggests: knitr, rmarkdown, testthat, @@ -72,5 +72,6 @@ Collate: 'rasterize.R' 'samc.R' 'survival.R' + 'utils-models.R' 'zzz.R' LinkingTo: Rcpp (>= 1.0.10), RcppEigen (>= 0.3.3.9.3), RcppThread (>= 2.1.3) diff --git a/LICENSE b/LICENSE index 10926e8..f36a7b7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies @@ -7,17 +7,15 @@ Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. 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 +our General Public Licenses are 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. +software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you @@ -26,44 +24,34 @@ 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. + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. The precise terms and conditions for copying, distribution and modification follow. @@ -72,7 +60,7 @@ modification follow. 0. Definitions. - "This License" refers to version 3 of the GNU General Public License. + "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. @@ -549,35 +537,45 @@ 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. + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. 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 +under version 3 of the GNU 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. +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. 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 +the GNU Affero 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 +Program specifies that a certain numbered version of the GNU Affero 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 +GNU Affero 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 +versions of the GNU Affero 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. @@ -632,44 +630,33 @@ 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) + + Copyright (C) {{ year }} {{ organization }} 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 + it under the terms of the GNU Affero 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. + GNU Affero General Public License for more details. - You should have received a copy of the GNU General Public License + You should have received a copy of the GNU Affero 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". + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. 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 +For more information on this, and how to apply and follow the GNU AGPL, see . - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. - diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..fab6548 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,659 @@ +GNU Affero General Public License +================================= + +_Version 3, 19 November 2007_ +_Copyright (C) 2007 Free Software Foundation, Inc. <>_ + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +## Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + +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. + +Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing +under this license. + +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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your +version supports such interaction) an opportunity to receive the +Corresponding Source of your version by providing access to the +Corresponding Source from a network server at no charge, through some +standard or customary means of facilitating copying of software. This +Corresponding Source shall include the Corresponding Source for any +work covered by version 3 of the GNU General Public License that is +incorporated pursuant to the following paragraph. + +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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for +the specific requirements. + +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 AGPL, see . diff --git a/NEWS.md b/NEWS.md index 2695152..3ba544b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,21 @@ +# samc 3.3.0 + +## New features + +- New input options for metrics + - cond_passage(samc, init, dest) + - dispersal(samc, origin, dest, time) + - distribution(samc, init, dest, time) + - mortality(samc, init, dest, time) + +## Other + +- Lot's of internal refactoring and consolidation. +- Various small memory and speed optimizations. +- Various small fixes +- License update + + # samc 3.2.1 ## Bug fix diff --git a/R/RcppExports.R b/R/RcppExports.R index 1053381..fc50d50 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -41,24 +41,12 @@ .Call('_samc_diagf_par_iter', PACKAGE = 'samc', M, threads) } -.psid_long <- function(M, psi, dg, SC) { - .Call('_samc_psid_long', PACKAGE = 'samc', M, psi, dg, SC) +.qpow_row <- function(M, vec, steps) { + .Call('_samc_qpow_row', PACKAGE = 'samc', M, vec, steps) } -.psid_long_iter <- function(M, psi, dg) { - .Call('_samc_psid_long_iter', PACKAGE = 'samc', M, psi, dg) -} - -.qpow_row <- function(M, row, steps) { - .Call('_samc_qpow_row', PACKAGE = 'samc', M, row, steps) -} - -.qpow_col <- function(M, col, steps) { - .Call('_samc_qpow_col', PACKAGE = 'samc', M, col, steps) -} - -.psiq <- function(M, psi, steps) { - .Call('_samc_psiq', PACKAGE = 'samc', M, psi, steps) +.qpow_col <- function(M, vec, steps) { + .Call('_samc_qpow_col', PACKAGE = 'samc', M, vec, steps) } .sum_qpowrv <- function(M, rv, steps) { @@ -77,39 +65,27 @@ .Call('_samc_f1_iter', PACKAGE = 'samc', M) } -.sum_qpow_row <- function(M, row, steps) { - .Call('_samc_sum_qpow_row', PACKAGE = 'samc', M, row, steps) -} - -.sum_qpow_col <- function(M, col, steps) { - .Call('_samc_sum_qpow_col', PACKAGE = 'samc', M, col, steps) -} - -.sum_psiqpow <- function(M, psi, steps) { - .Call('_samc_sum_psiqpow', PACKAGE = 'samc', M, psi, steps) -} - -.f_row <- function(M, row, SC) { - .Call('_samc_f_row', PACKAGE = 'samc', M, row, SC) +.sum_qpow_row <- function(M, vec, steps) { + .Call('_samc_sum_qpow_row', PACKAGE = 'samc', M, vec, steps) } -.f_row_iter <- function(M, row) { - .Call('_samc_f_row_iter', PACKAGE = 'samc', M, row) +.sum_qpow_col <- function(M, vec, steps) { + .Call('_samc_sum_qpow_col', PACKAGE = 'samc', M, vec, steps) } -.f_col <- function(M, col, SC) { - .Call('_samc_f_col', PACKAGE = 'samc', M, col, SC) +.f_row <- function(M, vec, SC) { + .Call('_samc_f_row', PACKAGE = 'samc', M, vec, SC) } -.f_col_iter <- function(M, col) { - .Call('_samc_f_col_iter', PACKAGE = 'samc', M, col) +.f_row_iter <- function(M, vec) { + .Call('_samc_f_row_iter', PACKAGE = 'samc', M, vec) } -.psif <- function(M, psi, SC) { - .Call('_samc_psif', PACKAGE = 'samc', M, psi, SC) +.f_col <- function(M, vec, SC) { + .Call('_samc_f_col', PACKAGE = 'samc', M, vec, SC) } -.psif_iter <- function(M, psi) { - .Call('_samc_psif_iter', PACKAGE = 'samc', M, psi) +.f_col_iter <- function(M, vec) { + .Call('_samc_f_col_iter', PACKAGE = 'samc', M, vec) } diff --git a/R/absorption.R b/R/absorption.R index be43024..5fdd6fa 100644 --- a/R/absorption.R +++ b/R/absorption.R @@ -1,5 +1,5 @@ -# Copyright (c) 2021 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R location-class.R NULL @@ -57,6 +57,7 @@ setGeneric( standardGeneric("absorption") }) +# TODO Add unit tests # absorption(samc) ---- #' @rdname absorption @@ -66,13 +67,27 @@ setMethod( function(samc) { .disable_conv(samc) - if (any(dim(samc@data@c_abs) == 0)) stop("No absorption components defined in the samc object", call. = FALSE) + c_abs = samc@data@c_abs + if (any(dim(c_abs) == 0)) stop("No absorption components defined in the samc object", call. = FALSE) + + if (samc@model$name == "CRW") { + c_abs = apply(c_abs, 2, function(x) { x[samc@crw_map[, 1]] }) + } - # TODO: possibly optimize using C++ - abs_mat <- Matrix::solve(samc@data@f, samc@data@c_abs) + # TODO: possibly optimize + abs_mat <- Matrix::solve(samc@data@f, c_abs) abs_mat <- as.matrix(abs_mat) + if (samc@model$name == "CRW") { + vec = as.vector(samc@prob_mat) + vec = vec[!is.na(vec)] + + abs_mat = vec * abs_mat + + abs_mat = apply(abs_mat, 2, function(x) { .summarize_crw(samc, x, sum) }) + } + colnames(abs_mat) <- colnames(samc@data@c_abs) return(abs_mat) @@ -110,21 +125,9 @@ setMethod( "absorption", signature(samc = "samc", init = "ANY", origin = "missing"), function(samc, init) { - .disable_crw(samc) - if (any(dim(samc@data@c_abs) == 0)) stop("No absorption components defined in the samc object", call. = FALSE) - if (samc@solver %in% c("direct", "iter")) { - check(samc, init) - - pv = .process_init(samc, init) - - pf = .psif(samc@data@f, pv, samc@.cache$sc) - } else if (samc@solver == "conv") { - pf = visitation(samc, init) - } else { - stop("Invalid method attribute in samc object.") - } + pf = visitation(samc, init) result = as.vector(pf %*% samc@data@c_abs) names(result) = colnames(samc@data@c_abs) diff --git a/R/check.R b/R/check.R index 2a24309..41bcfc1 100644 --- a/R/check.R +++ b/R/check.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details.. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R NULL @@ -119,7 +119,7 @@ setMethod( data = terra::values(a, row = r, nrows = 1) if (any(is.infinite(data))) stop("Data contains Inf or -Inf", call. = FALSE) - if (any(is.nan(data))) stop("Data contains Inf or -Inf", call. = FALSE) + if (any(is.nan(data))) stop("Data contains NaN", call. = FALSE) data = rowSums(is.finite(data)) if (any(data > 0 & data < n)) stop("NA mismatch in input data", call. = FALSE) @@ -209,7 +209,9 @@ setMethod( if (!isTRUE(all.equal(names(b), a@names))) stop("Names of the vector must match the names of the transient states in the P matrix", call. = FALSE) - if (any(!is.finite(b)) || any(b < 0)) stop("Input must only contain positive numeric values", call. = FALSE) + if (any(!is.finite(b)) || any(b < 0) || any(is.na(b))) stop("Input must only contain positive numeric values", call. = FALSE) if (length(b) != length(a@data@t_abs)) stop("Input length does not match number of transient states", call. = FALSE) + + if (sum(b) <= 0) stop("Input must contain at least one positive numeric value", call. = FALSE) }) diff --git a/R/cond_passage.R b/R/cond_passage.R index ede3e89..ecae499 100644 --- a/R/cond_passage.R +++ b/R/cond_passage.R @@ -1,5 +1,5 @@ -# Copyright (c) 2020 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R location-class.R NULL @@ -52,7 +52,7 @@ NULL #' @template section-perf #' #' @template param-samc -#' @param init Placeholder/not currently implemented. +#' @template param-init #' @template param-origin #' @template param-dest #' @@ -75,7 +75,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location"), function(samc, dest) { .disable_conv(samc) - .disable_crw(samc) if (samc@clumps == -1) warning("Unknown number of clumps in data. If the function crashes, it may be due to the transition matrix being discontinuous.", call. = FALSE) @@ -86,36 +85,47 @@ setMethod( if (length(dest) != 1) stop("dest must be a single location that refers to a cell in the landscape", call. = FALSE) - dest <- .process_locations(samc, dest) + dest = .process_locations(samc, dest) + + if (samc@model$name == "RW") { + vec = logical(samc@nodes) + vec[dest] = TRUE + } else if (samc@model$name == "CRW") { + vec = (samc@crw_map[,1] == dest) + } else { + stop("Unexpected model", call. = FALSE) + } - Q <- samc$q_matrix - qj <- Q[-dest, dest] - Qj <- Q[-dest, -dest] + Q = samc$q_matrix - Qj@x <- -Qj@x - Matrix::diag(Qj) <- Matrix::diag(Qj) + 1 + q = Q[, vec, drop = FALSE] + q = Matrix::rowSums(q) + q[vec] = 1 + + Q[vec, ] = 0 + Q[, vec] = 0 + + Q@x = -Q@x + Matrix::diag(Q) = Matrix::diag(Q) + 1 if (samc@solver == "iter") { - t <- as.numeric(.cond_t_iter(Qj, qj)) + t = .cond_t_iter(Q, q) } else { - t <- as.numeric(.cond_t(Qj, qj)) + t = .cond_t(Q, q) } - # insert 0 element back into vector so output length is same original data - final <- 1:(length(t) + 1) - names(final) <- samc$names - - j <- 1 - for (i in 1:length(final)) { - if (final[dest] == i) { - final[dest] <- 0 - next - } - final[i] <- t[j] - j <- j + 1 + if (samc@model$name == "RW") { + res = t$fb / t$b + } else if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + res = .summarize_crw(samc, (pv * t$fb), sum) / .summarize_crw(samc, pv * t$b, sum) # Works } - return(final) + names(res) = samc$names + + return(res) }) # cond_passage(samc, origin, dest) ---- @@ -125,7 +135,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location"), function(samc, origin, dest) { .disable_conv(samc) - .disable_crw(samc) if(length(origin) != length(dest)) stop("The 'origin' and 'dest' parameters must have the same number of values", call. = FALSE) @@ -146,3 +155,31 @@ setMethod( return(result) }) + +# cond_passage(samc, init, dest) ---- +#' @rdname cond_passage +setMethod( + "cond_passage", + signature(samc = "samc", init = "ANY", origin = "missing", dest = "location"), + function(samc, init, dest) { + .disable_conv(samc) + + if(length(origin) != length(dest)) + stop("The 'origin' and 'dest' parameters must have the same number of values", call. = FALSE) + + origin <- .process_locations(samc, origin) + dest <- .process_locations(samc, dest) + + result <- vector(mode = "numeric", length = length(origin)) + + unique_dest <- unique(dest) + + for (d in unique_dest) { + t <- cond_passage(samc, dest = d) + # adj_origin <- origin + # adj_origin[origin > d] <- adj_origin[origin > d] - 1 + result[dest == d] <- t[origin[dest == d]] + } + + return(result) + }) diff --git a/R/data.R b/R/data.R index d83182c..bf3f7f1 100644 --- a/R/data.R +++ b/R/data.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019-2023 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' Simple split corridor example #' diff --git a/R/dispersal.R b/R/dispersal.R index 4767952..c2553dc 100644 --- a/R/dispersal.R +++ b/R/dispersal.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R location-class.R visitation.R NULL @@ -111,6 +111,25 @@ setGeneric( standardGeneric("dispersal") }) +# dispersal(samc, origin, dest, time) ---- +#' @rdname dispersal +setMethod( + "dispersal", # TODO add unit tests + signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "numeric"), + function(samc, origin, dest, time) { + if (is(origin, "matrix")) { + if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) + } else { + if (length(origin) != 1) + stop("origin can only contain a single value for this version of the function", call. = FALSE) + } + + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) + + return(dispersal(samc, init, dest=dest, time = time)) + }) + # dispersal(samc, dest, time) ---- #' @rdname dispersal setMethod( @@ -118,7 +137,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "numeric"), function(samc, dest, time) { .disable_conv(samc) - .disable_crw(samc) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) @@ -126,30 +144,44 @@ setMethod( dest <- .process_locations(samc, dest) .validate_time_steps(time) - q <- samc$q_matrix - qv <- q[, dest] - qv <- qv[-dest] - q <- q[-dest, -dest] + if (samc@model$name == "RW") { + vec = logical(samc@nodes) + vec[dest] = TRUE + } else if (samc@model$name == "CRW") { + vec = (samc@crw_map[,1] == dest) + } else { + stop("Unexpected model", call. = FALSE) + } + + q = samc$q_matrix + + qv = q[, vec, drop = FALSE] + qv[vec ,] = 0 + qv = Matrix::rowSums(qv) + + q[, vec] = 0 + q[vec, ] = 0 q2 = q - q2@x <- -q2@x - Matrix::diag(q2) <- Matrix::diag(q2) + 1 + q2@x = -q2@x + Matrix::diag(q2) = Matrix::diag(q2) + 1 time <- c(0, time) if (samc@solver == "iter") { - res <- .sum_qn_q_iter(q, q2, qv, time) + res = .sum_qn_q_iter(q, q2, qv, time) } else { - res <- .sum_qn_q(q, q2, qv, time) + res = .sum_qn_q(q, q2, qv, time) } - res <- lapply(res, as.vector) + res = lapply(res, as.vector) + + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] - # Element for i=j is missing, so fill in with NA - res <- lapply(res, function(x) { - lx <- length(x) - y <- c(x[0:(dest-1)], NA, x[dest:(lx + 1)]) - return(y[1:(lx + 1)])}) + res = lapply(res, function(x) .summarize_crw(samc, pv * x, sum)) + } if (length(res) == 1) { return(res[[1]]) @@ -165,7 +197,6 @@ setMethod( signature(samc = "samc", init = "ANY", origin = "missing", dest = "location", time = "numeric"), function(samc, init, dest, time) { .disable_conv(samc) - .disable_crw(samc) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) @@ -176,6 +207,8 @@ setMethod( pv <- .process_init(samc, init) + if (samc@model$name == "CRW") pv = .summarize_crw(samc, pv, sum) + d <- dispersal(samc, dest = dest, time = time) pv <- pv[-dest] @@ -224,28 +257,15 @@ setMethod( if (is(origin, "matrix")) { if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) + } else { + if (length(origin) != 1) + stop("origin can only contain a single value for this version of the function", call. = FALSE) } - origin <- .process_locations(samc, origin) - - if (!samc@.cache$dgf_exists) { - if (samc@solver == "iter") { - dg <- samc:::.diagf_par_iter(samc@data@f, samc@threads) - } else { - dg <- samc:::.diagf_par(samc@data@f, samc@threads) - } - - samc@.cache$dgf <- dg - samc@.cache$dgf_exists <- TRUE - } - - f_row <- visitation(samc, origin = origin) - f_row[origin] <- f_row[origin] - 1 + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) - result <- as.vector(f_row/samc@.cache$dgf) - names(result) <- colnames(samc$q_matrix) # TODO update based on names changes? Check for other similiar situations - - return(result) + return(dispersal(samc, init)) }) # dispersal(samc, dest) ---- @@ -255,7 +275,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "missing"), function(samc, dest) { .disable_conv(samc) - .disable_crw(samc) dest <- .process_locations(samc, dest) @@ -276,7 +295,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "missing"), function(samc, origin, dest) { .disable_conv(samc) - .disable_crw(samc) origin <- .process_locations(samc, origin) dest <- .process_locations(samc, dest) @@ -302,12 +320,9 @@ setMethod( signature(samc = "samc", init = "ANY", origin = "missing", dest = "missing", time = "missing"), function(samc, init) { .disable_conv(samc) - .disable_crw(samc) check(samc, init) - pv <- .process_init(samc, init) - if (!samc@.cache$dgf_exists) { if (samc@solver == "iter") { dg <- samc:::.diagf_par_iter(samc@data@f, samc@threads) @@ -319,13 +334,17 @@ setMethod( samc@.cache$dgf_exists <- TRUE } - if (samc@solver == "iter") { - disp <- .psid_long_iter(samc@data@f, pv, samc@.cache$dgf) - } else { - disp <- .psid_long(samc@data@f, pv, samc@.cache$dgf, samc@.cache$sc) + vis = visitation(samc, init) + + dg = samc@.cache$dgf + init = .process_init(samc, init) + + if (samc@model$name == "CRW") { + dg = .summarize_crw(samc, dg, sum) - .summarize_crw(samc, dg, length) + 1 + init = .summarize_crw(samc, init, sum) } - return(as.vector(disp)) + return((vis - init)/dg) }) @@ -336,7 +355,6 @@ setMethod( signature(samc = "samc", init = "ANY", origin = "missing", dest = "location", time = "missing"), function(samc, init, dest) { .disable_conv(samc) - .disable_crw(samc) check(samc, init) @@ -344,5 +362,9 @@ setMethod( dj <- dispersal(samc, dest = dest) + if (samc@model$name == "CRW") { + pv = .summarize_crw(samc, pv, sum) + } + return(as.numeric(pv %*% dj)) }) diff --git a/R/distribution.R b/R/distribution.R index 3c03b2f..c9f18d2 100644 --- a/R/distribution.R +++ b/R/distribution.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R visitation.R NULL @@ -114,6 +114,16 @@ setMethod( res <- res %*% q } + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + res = diag(pv) %*% res + + res = apply(res, 1, function(x) samc:::.summarize_crw(samc, x, sum)) + res = apply(res, 1, function(x) samc:::.summarize_crw(samc, x, sum)) # Same margin because results of last are transposed + } + return(res) }) @@ -123,30 +133,16 @@ setMethod( "distribution", signature(samc = "samc", init = "missing", origin = "location", dest = "missing", time = "numeric"), function(samc, origin, time) { - .disable_conv(samc) - if (is(origin, "matrix")) { if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) } else { - if (length(origin) != 1) - stop("origin can only contain a single value for this version of the function", call. = FALSE) + if (length(origin) != 1) stop("origin can only contain a single value for this version of the function", call. = FALSE) } - origin <- .process_locations(samc, origin) - - .validate_time_steps(time) - - q <- samc$q_matrix - - time <- c(1, time) + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) - mov <- .qpow_row(q, origin, time) - mov <- lapply(mov, as.vector) - if (length(mov) == 1) { - return((mov[[1]])) - } else { - return(mov) - } + return(distribution(samc, init, time = time)) }) # distribution(samc, dest, time) ---- @@ -156,7 +152,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "numeric"), function(samc, dest, time) { .disable_conv(samc) - .disable_crw(samc) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) @@ -164,17 +159,33 @@ setMethod( dest <- .process_locations(samc, dest) .validate_time_steps(time) - q <- samc$q_matrix + q = samc$q_matrix + + time = c(1, time) + + if (samc@model$name == "RW") { + vec = numeric(samc@nodes) + vec[dest] = 1 + } else if (samc@model$name == "CRW") { + vec = as.numeric(samc@crw_map[,1] == dest) + } else { + stop("Unexpected model", call. = FALSE) + } + + res = .qpow_col(q, vec, time) + res = lapply(res, as.vector) - time <- c(1, time) + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] - mov <- .qpow_col(q, dest, time) - mov <- lapply(mov, as.vector) + res = lapply(res, function(x) .summarize_crw(samc, pv * x, sum)) + } - if (length(mov) == 1) { - return((mov[[1]])) + if (length(res) == 1) { + return((res[[1]])) } else { - return(mov) + return(res) } }) @@ -185,22 +196,14 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "numeric"), function(samc, origin, dest, time) { .disable_conv(samc) - .disable_crw(samc) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) - dest <- .process_locations(samc, dest) - - mov <- distribution(samc, origin = origin, time = time) + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) - if (is.list(mov)){ - return(lapply(mov, "[", dest)) - } else if (is.vector(mov)) { - return(mov[dest]) - } else { - stop("This should not have been possible. Please submit a report with a fully reproducible and simplified example.", call. = FALSE) - } + return(distribution(samc, init, dest = dest, time = time)) }) # distribution(samc, init, time) ---- @@ -210,7 +213,6 @@ setMethod( signature(samc = "samc", init = "ANY", origin = "missing", dest = "missing", time = "numeric"), function(samc, init, time) { check(samc, init) - .disable_crw(samc) pv <- .process_init(samc, init) @@ -221,10 +223,12 @@ setMethod( time = c(0, time) - res = .psiq(q, pv, time) + res = .qpow_row(q, pv, time) res = lapply(res, as.vector) + if (samc@model$name == "CRW") res = lapply(res, function(x) .summarize_crw(samc, x, sum)) + if (length(res) == 1) { return(res[[1]]) } else { @@ -240,3 +244,27 @@ setMethod( stop("Invalid method attribute in samc object.") } }) + +# distribution(samc, init, dest, time) ---- +#' @rdname distribution +setMethod( + "distribution", + signature(samc = "samc", init = "ANY", origin = "missing", dest = "location", time = "numeric"), + function(samc, init, dest, time) { + .disable_conv(samc) + + if (length(dest) != 1) + stop("dest can only contain a single location for this version of the function", call. = FALSE) + + dest = .process_locations(samc, dest) + + res = distribution(samc, init, time = time) + + if (is.list(res)){ + return(lapply(res, "[", dest)) + } else if (is.vector(res)) { + return(res[dest]) + } else { + stop("This should not have been possible. Please submit a report with a fully reproducible and simplified example.", call. = FALSE) + } + }) diff --git a/R/generics.R b/R/generics.R index 5156734..9ef70b8 100644 --- a/R/generics.R +++ b/R/generics.R @@ -1,5 +1,5 @@ -# Copyright (c) 2021 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R NULL diff --git a/R/internal-classes.R b/R/internal-classes.R index 5f0cfd7..642aa5c 100644 --- a/R/internal-classes.R +++ b/R/internal-classes.R @@ -1,5 +1,5 @@ -# Copyright (c) 2021 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. NULL #' data class diff --git a/R/internal-functions.R b/R/internal-functions.R index 16086e4..be0a34b 100644 --- a/R/internal-functions.R +++ b/R/internal-functions.R @@ -1,22 +1,26 @@ -# Copyright (c) 2020-2023 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. -# +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. + # This file is for internal functions. They are subject to change and should not # be used by users. -# + #' RW function #' #' An internal function for creating RW samc matrix #' #' @noRd -.rw <- function(x, absorption, fidelity, fun, dir, sym) { - if (is(fun, "function")) { +.rw <- function(x, absorption, fidelity, model) { + dir = model$dir + fun = model$fun + sym = model$sym + + if (model$name == "RW") { tr = .tr_vals(x, fun, dir) - } else if (fun == "1/mean(x)") { - tr = .tr_vals_res(x, dir) + } else if (model$name == "SSF") { + tr = .tr_vals_ssf(x, fun, dir, model$ssc) } else { - stop("Invalid transition function defined", call. = FALSE) + stop("", call. = FALSE) } nedges = sum(is.finite(tr)) @@ -139,19 +143,14 @@ mat } + #' CRW function #' #' An internal function for creating RW samc objects #' #' @noRd .crw <- function(x, absorption, fidelity, fun, dir, sym = TRUE, model) { - if (is(fun, "function")) { - tr = .tr_vals(x, fun, dir) - } else if (fun == "1/mean(x)") { - tr = .tr_vals_res(x, dir) - } else { - stop("Invalid transition function defined", call. = FALSE) - } + tr = .tr_vals(x, fun, dir) edge_counts = sum(is.finite(tr)) edge_nums = tr @@ -165,6 +164,8 @@ edge_counts = sum(is.finite(tr)) + mu = circular::circular(0) + # Angle matrix # TODO make sure works for 4 directions dir_vec = matrix(c(-1, 1, @@ -184,7 +185,7 @@ mag_v1 = sqrt(sum(dir_vec[r, ]^2)) mag_v2 = sqrt(sum(dir_vec[c, ]^2)) - ang_mat[r, c] = circular::dvonmises(circular::circular(acos(sum(dir_vec[r, ] * dir_vec[c, ]) / (mag_v1 * mag_v2))), mu = circular::circular(0), kappa = model$kappa) + ang_mat[r, c] = circular::circular(acos(sum(dir_vec[r, ] * dir_vec[c, ]) / (mag_v1 * mag_v2))) } } @@ -256,6 +257,7 @@ for (r in 1:nrows) { fid = terra::values(fidelity, mat = FALSE, row = r, nrows = 1) vals = 1 - fid - terra::values(absorption, mat = FALSE, row = r, nrows = 1) + kappa_vals = terra::values(model$kappa, mat = FALSE, row = r, nrows = 1) for (c in 1:ncols) { cell = cell + 1 if (is.finite(vals[c])) { @@ -287,7 +289,7 @@ e2_num = edge_nums[e2] mat_p_count[e2_num] = mat_p_count[e2_num] + 1 - res = tr[e2] * ang_mat[d, dv] + res = tr[e2] * circular::dvonmises(ang_mat[d, dv], mu = mu, kappa = kappa_vals[c]) rs = rs + res row_indices[dv] = mat_p[e2_num] + mat_p_count[e2_num] @@ -321,9 +323,15 @@ #View(as.matrix(mat)) + + dim(tr) = c(dir, length(tr)/dir) + tr = scale(tr, FALSE, colSums(tr, na.rm = TRUE)) + attr(tr, 'scaled:scale') = NULL + return( list(tr = mat, crw = crw_map, + prob = tr, abs = terra::values(absorption)[cell_nums[crw_map[,1]]]) ) } @@ -345,25 +353,42 @@ dir = c(1:4, 6:9) } - for (r in 1:nrows) { - vals = terra::focalValues(data, 3, r,1) + if (is(fun, "function")) { + for (r in 1:nrows) { + vals = terra::focalValues(data, 3, r,1) - for (c in 1:ncols) { - v = vals[c, 5] - for (d in dir) { - index = index + 1 + for (c in 1:ncols) { + v = vals[c, 5] + for (d in dir) { + index = index + 1 - result[index] = fun(c(v, vals[c, d])) / dist[r, d] + result[index] = fun(c(v, vals[c, d])) / dist[r, d] + } + } + } + } else if (fun == "1/mean(x)") { + for (r in 1:nrows) { + vals = terra::focalValues(data, 3, r,1) + + for (c in 1:ncols) { + v = vals[c, 5] + for (d in dir) { + index = index + 1 + + result[index] = 2 / ((v + vals[c, d]) * dist[r, d]) + } } } + } else { + stop("Invalid transition function defined", call. = FALSE) } result } -.tr_vals_res = function(data, dir) { +.tr_vals_ssf = function(data, fun, dir, ssc) { nrows = terra::nrow(data) ncols = terra::ncol(data) @@ -371,7 +396,7 @@ result = numeric(nrows * ncols * dir) index = 0 - dist = .build_lookup_mat(data, dir) + dist = .build_lookup_mat(data, dir)^(ssc) if (dir == 4) { dir = c(2, 4, 6, 8) @@ -379,18 +404,33 @@ dir = c(1:4, 6:9) } - for (r in 1:nrows) { - vals = terra::focalValues(data, 3, r,1) + if (is(fun, "function")) { + for (r in 1:nrows) { + vals = terra::focalValues(data, 3, r,1) - for (c in 1:ncols) { - v = vals[c, 5] - for (d in dir) { - index = index + 1 + for (c in 1:ncols) { + v = vals[c, 5] + for (d in dir) { + index = index + 1 - result[index] = 2 / ((v + vals[c, d]) * dist[r, d]) + result[index] = fun(c(v, vals[c, d])) * dist[r, d] + } + } + } + } else if (fun == "x[2]") { + for (r in 1:nrows) { + vals = terra::focalValues(data, 3, r,1) + for (c in 1:ncols) { + for (d in dir) { + index = index + 1 + + result[index] = vals[c, d] * dist[r, d] + } } } + } else { + stop("Invalid transition function defined", call. = FALSE) } result @@ -596,7 +636,7 @@ # limit represents 24.7 years. There is flexibility to increase the limit # if a justification can be made for it, but it's far more likely that # users will generally want far fewer time steps for ecologically relevant - # results and to avoid the cummulative precision issues.", call. = FALSE) + # results and to avoid the cumulative precision issues.", call. = FALSE) } @@ -620,7 +660,7 @@ if (any(x < 1)) stop("All location values must be positive (greater than 0)", call. = FALSE) - if (any(x > nrow(samc$q_matrix))) + if (any(x > samc@nodes)) stop("Location values cannot exceed the number of nodes in the landscape", call. = FALSE) } @@ -687,12 +727,8 @@ setMethod( ".process_locations", signature(samc = "samc", x = "numeric"), function(samc, x) { + .validate_locations(samc, x) - if (samc@model$name == "CRW") { - stop("CRW model requires a list with location and direction.", call. = FALSE) - } else { - .validate_locations(samc, x) - } return(x) }) @@ -700,84 +736,32 @@ setMethod( ".process_locations", signature(samc = "samc", x = "character"), function(samc, x) { - .validate_names(samc$names, x) - return(match(x, samc$names)) + return(.process_locations(samc, match(x, samc$names))) }) -#' Validate transition args +#' Map Location #' -#' Validates the transition args for the samc() function +#' Map a location #' #' @param x A list #' @noRd -.validate_model <- function(x, method) { - args <- c("name", "fun", "dir", "sym") - names <- names(x) - - dup_args <- names[duplicated(names)] - if (length(dup_args) > 0) - stop(paste("Duplicate argument in model:", dup_args), call. = FALSE) - - if (!("name" %in% names)) { - x$name = "RW" - names = c(names, "name") - } - - if (!x$name %in% c("RW", "CRW")) stop("Invalid model name", call. = FALSE) - - missing_args <- args[!(args %in% names)] - if (length(missing_args) > 0) - stop(paste("Missing argument in model:", missing_args), call. = FALSE) - - if (!(is(x$fun, "function") || is(x$fun, "character"))) { - stop("'fun' must be a supported named function or a user defined function") - } else if (!(x$dir %in% c(4, 8))) { - stop("`dir` must be set to either 4 or 8", call. = FALSE) - } else if (!is(x$sym, "logical")) { - stop("`sym` must be set to either TRUE or FALSE", call. = FALSE) - } - - if (method == "conv") { - if (x$name != "RW") stop("Convolution currently only supports the 'RW' model.") - if (!is(x$fun, "character")) { - stop("Convolution currently only supports the '1/mean(x)' named function.") - } else if (x$fun != "1/mean(x)") { - stop("Convolution currently only supports the '1/mean(x)' named function.") - } - } - - - if (x$name == "CRW") { - args = c(args, "dist", "kappa") - } - +.map_location <- function(samc, x) { + if (samc@source == "transition") { + vec = numeric(samc@nodes) + vec[x] = 1 + names(vec) = samc@names - unknown_args <- names[!(names %in% args)] - if (length(unknown_args) > 0) - stop(paste("Unknown argument in model:", unknown_args), call. = FALSE) - - if (x$name == "CRW") { - if (x$dist == "vonMises") { - if (!is(x$kappa, "numeric")) - stop("kappa must be single non-negative numeric value.", call. = FALSE) - - if (length(x$kappa) != 1) - stop("kappa must be single non-negative numeric value.", call. = FALSE) - - if (!is.finite(x$kappa)) - stop("kappa must be single non-negative numeric value.", call. = FALSE) - - if (x$kappa < 0) - stop("kappa must be single non-negative numeric value.", call. = FALSE) - } else { - stop(paste("Invalid distribution name:", x$dist), call. = FALSE) - } + return(vec) + } else { + df = data.frame(cell = terra::cells(samc@map), + vec = numeric(samc@nodes)) + df$vec[x] = 1 } - return(x) + return(.build_map(samc, df)) } @@ -910,7 +894,14 @@ setMethod( function(samc, x) { if (any(!is.finite(x)) || any(x < 0)) stop("`init` input must only contain positive numeric values") - if (length(x) != length(samc@data@t_abs)) stop("`init` input length does not match number of transient states") + if (length(x) != samc@nodes) stop("`init` input length does not match number of nodes") + + + if (samc@model$name == "CRW") { + x = sweep(samc@prob_mat[, terra::cells(samc@map)], 2, x, "*") + dim(x) = NULL + x = x[!is.na(x)] + } return(x) }) @@ -962,3 +953,17 @@ setMethod( .disable_conv <- function(samc) { if (samc@solver == "conv") stop("Metric/parameter combinaton not currently supported for the convolution algorithm", call. = FALSE) } + + +#' Summarize CRW +#' +#' Summarize CRW +#' +#' @param samc samc model +#' @noRd +.summarize_crw <- function(samc, vec, fun) { + if (length(vec) != nrow(samc@crw_map)) + stop("The length of the vector does not match the number of non-NA cells in the landscape data", call. = FALSE) + + aggregate(vec ~ samc@crw_map[, 1], FUN = fun)$vec +} diff --git a/R/locate.R b/R/locate.R index 899c39d..e107fc7 100644 --- a/R/locate.R +++ b/R/locate.R @@ -1,5 +1,5 @@ -# Copyright (c) 2020 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details.. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R NULL diff --git a/R/location-class.R b/R/location-class.R index 1c02f79..5d14505 100644 --- a/R/location-class.R +++ b/R/location-class.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' location class diff --git a/R/map.R b/R/map.R index 81d4228..2169696 100644 --- a/R/map.R +++ b/R/map.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include check.R samc-class.R NULL @@ -42,29 +42,17 @@ setGeneric( setMethod( "map", signature(samc = "samc", vec = "numeric"), - function(samc, vec){ + function(samc, vec) { + # TODO make work for transition matrices if (samc@source == "transition") stop("This function cannot be used for samc objects created from transition matrices", call. = FALSE) - if (samc@model$name == "CRW") { - vec = aggregate(vec ~ samc@crw_map[, 1], FUN = mean)$vec - } - if (length(vec) != length(terra::cells(samc@map))) stop("The length of the vector does not match the number of non-NA cells in the landscape data", call. = FALSE) - ras <- as.numeric(samc@map) - - ras[terra::cells(ras)] <- vec + df = data.frame(cell = terra::cells(samc@map), + vec = vec) - if (samc@source == "SpatRaster") { - return(ras) - } else if (samc@source == "RasterLayer") { - return(raster::raster(ras)) - } else if (samc@source == "matrix") { - return(as.matrix(ras, wide = TRUE)) - } else { - stop("An unexpected error occurred. Please report as a bug with a reproducible example", call. = FALSE) - } + .build_map(samc, df) }) #' @rdname map @@ -72,30 +60,49 @@ setMethod( "map", signature(samc = "samc", vec = "list"), function(samc, vec){ - if (samc@source == "transition") stop("This function cannot be used for samc objects created from transition matrices", call. = FALSE) lapply(vec, function(x){ - if (!inherits(x, "numeric")) - stop("List contains invalid item(s); all entries must be numeric vectors.", call. = FALSE) - if (length(x) != length(terra::cells(samc@map))) - stop("The length of one or more vectors in the list does not match the number of non-NA cells in the landscape data", call. = FALSE) + map(samc, x) }) + }) - res <- lapply(vec, function(x){ - ras <- samc@map - ras[terra::cells(ras)] <- x +#' Build map +#' +#' Internal function to map a df to various objects +#' +#' @param samc samc +#' @param df df +#' @noRd +.build_map = function(samc, df) { + ras_base = as.numeric(samc@map) - if (samc@source == "SpatRaster") { - return(ras) - } else if (samc@source == "RasterLayer") { - return(raster::raster(ras)) - } else if (samc@source == "matrix") { - return(as.matrix(ras, wide = TRUE)) - } else { - stop("An unexpected error occurred. Please report as a bug with a reproducible example", call. = FALSE) - } - }) + ras_list = lapply(sort(colnames(df)[-1]), function (x) { + ras = ras_base + ras[terra::cells(ras)] = df[x] - return(res) + return(ras) }) + + ras = terra::rast(ras_list) + + if (samc@source == "SpatRaster") { + return(ras) + } else if (samc@source == "RasterLayer") { + if (terra::nlyr(ras) > 1) { + return(raster::stack(ras)) + } else { + return(raster::raster(ras)) + } + } else if (samc@source == "matrix") { + if (terra::nlyr(ras) > 1) { + return(lapply(ras, function(x) { + as.matrix(x, wide = TRUE) + })) + } else { + return(as.matrix(ras, wide = TRUE)) + } + } else { + stop("An unexpected error occurred. Please report as a bug with a reproducible example", call. = FALSE) + } +} diff --git a/R/mortality.R b/R/mortality.R index 8d3c03d..e7eeb61 100644 --- a/R/mortality.R +++ b/R/mortality.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019-2023 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R location-class.R visitation.R NULL @@ -171,6 +171,17 @@ setMethod( q_n <- solve(qi - q) %*% (qi - qt) bt <- q_n %*% r + + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + bt = diag(pv) %*% bt + + bt = apply(bt, 1, function(x) samc:::.summarize_crw(samc, x, sum)) + bt = apply(bt, 1, function(x) samc:::.summarize_crw(samc, x, sum)) # Same margin because results of last are transposed + } + return(bt) }) @@ -184,7 +195,8 @@ setMethod( mort = visitation(samc, origin = origin, time = time) - rdg <- samc@data@t_abs + rdg = if (samc@model$name == "CRW") { .summarize_crw(samc, samc@data@t_abs, mean) } + else { samc@data@t_abs } if (is.list(mort)) { return(lapply(mort, function(x){as.vector(x * rdg)})) @@ -200,7 +212,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "numeric"), function(samc, dest, time) { .disable_conv(samc) - .disable_crw(samc) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) @@ -212,7 +223,16 @@ setMethod( rdg <- samc@data@t_abs - rdg[-dest] <- 0 + if (samc@model$name == "RW") { + vec = logical(samc@nodes) + vec[dest] = TRUE + } else if (samc@model$name == "CRW") { + vec = (samc@crw_map[,1] == dest) + } else { + stop("Unexpected model", call. = FALSE) + } + + rdg[!vec] <- 0 time <- c(1, time) @@ -220,6 +240,13 @@ setMethod( mort <- lapply(mort, as.vector) + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + mort = lapply(mort, function(x) .summarize_crw(samc, pv * x, sum)) + } + if (length(mort) == 1) { return(mort[[1]]) } else { @@ -234,7 +261,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "numeric"), function(samc, origin, dest, time) { .disable_conv(samc) - .disable_crw(samc) dest <- .process_locations(samc, dest) @@ -255,12 +281,12 @@ setMethod( "mortality", signature(samc = "samc", init = "ANY", origin = "missing", dest = "missing", time = "numeric"), function(samc, init, time) { - .disable_crw(samc) if (samc@solver %in% c("direct", "iter")) { mort = visitation(samc, init = init, time = time) - rdg <- samc@data@t_abs + rdg = if (samc@model$name == "CRW") { .summarize_crw(samc, samc@data@t_abs, mean) } + else { samc@data@t_abs } if (is.list(mort)) { return(lapply(mort, function(x){as.vector(x * rdg)})) @@ -271,13 +297,29 @@ setMethod( res = visitation(samc, init, time = time) + t_abs = samc@data@t_abs - return(res * samc@data@t_abs) + return(res * t_abs) } else { stop("Invalid method attribute in samc object.") } }) +# mortality(samc, init, dest, time) ---- +#' @rdname mortality +setMethod( + "mortality", + signature(samc = "samc", init = "ANY", origin = "missing", dest = "location", time = "numeric"), + function(samc, init, dest, time) { + .disable_conv(samc) + + dest = .process_locations(samc, dest) + + res = mortality(samc, init, time = time) + + return(res[dest]) + }) + # mortality(samc) ---- #' @rdname mortality setMethod( @@ -294,6 +336,9 @@ setMethod( dimnames(f) <- dimnames(samc$q_matrix) # Not sure why dimnames aren't carrying through later calculations rdg <- samc@data@t_abs + + if (samc@model$name == "CRW") rdg = .summarize_crw(samc, rdg, mean) + r <- Matrix::sparseMatrix(i = 1:length(rdg), j = 1:length(rdg), x = rdg, @@ -326,19 +371,17 @@ setMethod( function(samc, origin) { .disable_conv(samc) - vis <- visitation(samc, origin = origin) - names(vis) <- samc$names - - mort <- vis * samc@data@t_abs - - if (ncol(samc@data@c_abs) > 0) { - mort <- list(total = mort) - for (n in colnames(samc@data@c_abs)) { - mort[[n]] <- vis * samc@data@c_abs[, n] - } + if (is(origin, "matrix")) { + if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) + } else { + if (length(origin) != 1) + stop("origin can only contain a single value for this version of the function", call. = FALSE) } - return(mort) + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) + + return(mortality(samc, init)) }) # mortality(samc, dest) ---- @@ -348,14 +391,16 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "missing"), function(samc, dest) { .disable_conv(samc) - .disable_crw(samc) dest <- .process_locations(samc, dest) vis <- visitation(samc, dest = dest) names(vis) <- samc$names - mort <- vis * samc@data@t_abs[dest] + t_abs = if (samc@model$name == "CRW") { .summarize_crw(samc, samc@data@t_abs, mean) } + else { samc@data@t_abs } + + mort <- vis * t_abs[dest] if (ncol(samc@data@c_abs) > 0) { mort <- list(total = mort) @@ -374,7 +419,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "missing"), function(samc, origin, dest) { .disable_conv(samc) - .disable_crw(samc) if(length(origin) != length(dest)) stop("The 'origin' and 'dest' parameters must have the same number of values", call. = FALSE) @@ -390,8 +434,10 @@ setMethod( } names(results) <- samc$names[dest] + t_abs = if (samc@model$name == "CRW") { .summarize_crw(samc, samc@data@t_abs, mean) } + else { samc@data@t_abs } - mort <- results * samc@data@t_abs[dest] + mort <- results * t_abs[dest] if (ncol(samc@data@c_abs) > 0) { mort <- list(total = mort) @@ -409,37 +455,47 @@ setMethod( "mortality", signature(samc = "samc", init = "ANY", origin = "missing", dest = "missing", time = "missing"), function(samc, init) { - .disable_crw(samc) - check(samc, init) - pv <- .process_init(samc, init) + res = visitation(samc, init) + t_abs = samc@data@t_abs - if (samc@solver %in% c("direct", "iter")) { - if (samc@solver == "iter") { - pf <- .psif_iter(samc@data@f, pv) - } else { - pf <- .psif(samc@data@f, pv, samc@.cache$sc) + if (samc@model$name == "CRW") t_abs = .summarize_crw(samc, t_abs, mean) + + mort = res * t_abs + + if (ncol(samc@data@c_abs) > 0) { + mort = list(total = mort) + for (n in colnames(samc@data@c_abs)) { + mort[[n]] = res * samc@data@c_abs[, n] } + } - names(pf) <- samc$names + return(mort) + }) - mort <- pf * samc@data@t_abs +# TODO: make work with mulstiple dest and it can be used for mortality(samc, origin, dest) +# mortality(samc, init, dest) ---- +#' @rdname mortality +setMethod( + "mortality", + signature(samc = "samc", init = "ANY", origin = "missing", dest = "location", time = "missing"), + function(samc, init, dest) { + .disable_conv(samc) - if (ncol(samc@data@c_abs) > 0) { - mort <- list(total = mort) - for (n in colnames(samc@data@c_abs)) { - mort[[n]] <- pf * samc@data@c_abs[, n] - } - } + dest = .process_locations(samc, dest) - return(mort) - } else if (samc@solver == "conv") { + vis = visitation(samc, init) - res = visitation(samc, init) + t_abs = if (samc@model$name == "CRW") { .summarize_crw(samc, samc@data@t_abs, mean) } + else { samc@data@t_abs } - return(res * samc@data@t_abs) - } else { - stop("Invalid method attribute in samc object.") + mort = vis[dest] * t_abs[dest] + + if (ncol(samc@data@c_abs) > 0) { + mort = append(mort, as.list(vis[dest] * samc@data@c_abs[dest, ])) + names(mort) = c("total", colnames(samc@data@c_abs)) } + + return(mort) }) diff --git a/R/pairwise.R b/R/pairwise.R index 41e1129..c35923a 100644 --- a/R/pairwise.R +++ b/R/pairwise.R @@ -1,5 +1,5 @@ -# Copyright (c) 2021 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details.. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R location-class.R NULL diff --git a/R/rasterize.R b/R/rasterize.R index 9bf1902..3e9155e 100644 --- a/R/rasterize.R +++ b/R/rasterize.R @@ -1,5 +1,5 @@ -# Copyright (c) 2022 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details.. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R NULL diff --git a/R/samc-class.R b/R/samc-class.R index a2a7715..15d3c57 100644 --- a/R/samc-class.R +++ b/R/samc-class.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include internal-classes.R NULL @@ -81,8 +81,10 @@ NULL #' @slot conv_cache Convolution cache #' @slot model List containing model info used to build the samc object #' @slot source Information about the data source for the P matrix +#' @slot nodes The number of nodes in the graph #' @slot map Used to verify landscape inputs and mapping of vector data #' @slot crw_map Matrix used to map location and direction to edges description +#' @slot prob_mat Matric for CRW probabilities #' @slot names Names of the transient states #' @slot clumps Number of discontinuous regions in data #' @slot override Used to prevent accidental use of memory intensive functions @@ -99,8 +101,10 @@ setClass( conv_cache = "ANY", model = "list", source = "character", + nodes = "integer", map = "SpatRaster", crw_map = "mat_null", + prob_mat = "mat_null", names = "char_null", clumps = "numeric", override = "logical", diff --git a/R/samc.R b/R/samc.R index 9bb1603..1b544f8 100644 --- a/R/samc.R +++ b/R/samc.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R check.R NULL @@ -133,7 +133,6 @@ setMethod( options = .validate_options(options) model = .validate_model(model, options$method) - tr_fun <- model$fun directions <-model$dir symm <- model$sym @@ -177,6 +176,7 @@ setMethod( conv_cache = NULL, model = model, source = "SpatRaster", + nodes = as.integer(terra::global(data, fun = "notNA")), map = data, crw_map = NULL, names = NULL, @@ -205,8 +205,8 @@ setMethod( gc() # Create the transition matrix if (options$method %in% c("direct", "iter")) { - if (model$name == "RW") { - samc_obj@data@f = .rw(data, absorption, fidelity, tr_fun, directions, symm) + if (model$name %in% c("RW", "SSF")) { + samc_obj@data@f = .rw(data, absorption, fidelity, model) gc() samc_obj@data@t_abs = as.vector(terra::values(absorption))[terra::cells(absorption)] @@ -215,7 +215,15 @@ setMethod( if (terra::is.lonlat(data)) warning("CRW does not properly adjust turning angles for lonlat yet.") - crw_list = .crw(data, absorption, fidelity, tr_fun, directions, symm, model) + if (is(model$kappa, "SpatRaster")) { + check(c(data, model$kappa)) + } else if (is.numeric(model$kappa)) { + model$kappa = data * 0 + model$kappa + } else { + stop("Invalid kappa") + } + + crw_list = .crw(data, absorption, fidelity, model$fun, directions, symm, model) #assign("myvar", crw_list) samc_obj@data@f = crw_list$tr gc() @@ -223,6 +231,8 @@ setMethod( samc_obj@data@t_abs = crw_list$abs samc_obj@crw_map = crw_list$crw + samc_obj@prob_mat = crw_list$prob + } else { stop("Unexpected error involving model name. Please report with a minimum reproducible example.", call. = FALSE) } @@ -399,6 +409,7 @@ setMethod( model = list(name = "RW"), crw_map = NULL, source = "transition", + nodes = as.integer(r - 1), map = terra::rast(), names = nm, clumps = -1, diff --git a/R/survival.R b/R/survival.R index 02e3f47..29cdb5e 100644 --- a/R/survival.R +++ b/R/survival.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R visitation.R NULL @@ -33,6 +33,7 @@ NULL #' #' @template param-samc #' @template param-init +#' @template param-origin #' #' @return See Details #' @@ -42,7 +43,7 @@ NULL setGeneric( "survival", - function(samc, init) { + function(samc, init, origin) { standardGeneric("survival") }) @@ -50,43 +51,52 @@ setGeneric( #' @rdname survival setMethod( "survival", - signature(samc = "samc", init = "missing"), + signature(samc = "samc", init = "missing", origin = "missing"), function(samc) { .disable_conv(samc) + # TODO If multiple dest becomes supported, this can be replaced with visitation(dest) if (samc@solver == "iter") { z = .f1_iter(samc@data@f) } else { z = .f1(samc@data@f, samc@.cache$sc) } - return(as.vector(z)) + if (samc@model$name == "CRW") { + vec = as.vector(samc@prob_mat) + vec = vec[!is.na(vec)] + + z = vec * z + z = .summarize_crw(samc, z, sum) + } + + return(z) }) -# survival(samc, init) ---- +# survival(samc, origin) ---- #' @rdname survival setMethod( "survival", - signature(samc = "samc", init = "ANY"), - function(samc, init) { - .disable_crw(samc) - - if (samc@solver %in% c("direct", "iter")) { - check(samc, init) - - pv <- .process_init(samc, init) - - sv <- survival(samc) - - surv <- pv %*% sv + signature(samc = "samc", init = "missing", origin = "location"), + function(samc, origin) { + if (is(origin, "matrix")) { + if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) + } else { + if (length(origin) != 1) + stop("origin can only contain a single value for this version of the function", call. = FALSE) + } - return(as.numeric(surv)) - } else if (samc@solver == "conv") { + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) - res = visitation(samc, init) + return(survival(samc, init = init)) + }) - return(sum(res)) - } else { - stop("Invalid method attribute in samc object.") - } +# survival(samc, init) ---- +#' @rdname survival +setMethod( + "survival", + signature(samc = "samc", init = "ANY", origin = "missing"), + function(samc, init) { + sum(visitation(samc, init)) }) diff --git a/R/utils-models.R b/R/utils-models.R new file mode 100644 index 0000000..ae5a4d8 --- /dev/null +++ b/R/utils-models.R @@ -0,0 +1,164 @@ +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. + +#' Validate model +#' +#' Validates the model for the samc() function +#' +#' @param x A list +#' @noRd +.validate_model <- function(x, method) { + names <- names(x) + + dup_args <- names[duplicated(names)] + if (length(dup_args) > 0) + stop(paste("Duplicate argument in model:", dup_args), call. = FALSE) + + if (!("name" %in% names)) { + x$name = "RW" + } + + switch( + as.character(x$name), + RW = .validate_rw(x, method), + CRW = .validate_crw(x, method), + SSF = .validate_ssf(x, method), + stop("Invalid model name", call. = FALSE) + ) + + return(x) +} + + +#' Validate transition args for CRW +#' +#' Validates the model for the samc() function +#' +#' @param x A list +#' @noRd +.validate_rw <- function(x, method) { + names <- names(x) + + args = c("name", "fun", "dir", "sym") + methods = c("direct", "iter", "conv") + + missing_args <- args[!(args %in% names)] + if (length(missing_args) > 0) + stop(paste("Missing argument in model:", missing_args), call. = FALSE) + + if (!(is(x$fun, "function") || is(x$fun, "character"))) { + stop("'fun' must be a supported named function or a user defined function") + } else if (!(x$dir %in% c(4, 8))) { + stop("`dir` must be set to either 4 or 8", call. = FALSE) + } else if (!is(x$sym, "logical")) { + stop("`sym` must be set to either TRUE or FALSE", call. = FALSE) + } + + if (!(method %in% methods)) + stop("Invalid method for model", call. = FALSE) + + if (method == "conv") { + if (!is(x$fun, "character")) { + stop("Convolution currently only supports the '1/mean(x)' named function.", call. = FALSE) + } else if (x$fun != "1/mean(x)") { + stop("Convolution currently only supports the '1/mean(x)' named function.", call. = FALSE) + } + } + + unknown_args <- names[!(names %in% args)] + if (length(unknown_args) > 0) + stop(paste("Unknown argument in model:", unknown_args), call. = FALSE) +} + +#' Validate transition args for RW +#' +#' Validates the model for the samc() function +#' +#' @param x A list +#' @noRd +.validate_crw <- function(x, method) { + names <- names(x) + + args = c("name", "fun", "dir", "sym", "dist", "kappa") + methods = c("direct", "iter") + + + missing_args <- args[!(args %in% names)] + if (length(missing_args) > 0) + stop(paste("Missing argument in model:", missing_args), call. = FALSE) + + if (!(is(x$fun, "function") || is(x$fun, "character"))) { + stop("'fun' must be a supported named function or a user defined function") + } else if (!(x$dir %in% c(4, 8))) { + stop("`dir` must be set to either 4 or 8", call. = FALSE) + } else if (!is(x$sym, "logical")) { + stop("`sym` must be set to either TRUE or FALSE", call. = FALSE) + } + + if (!(method %in% methods)) + stop("Invalid method for model", call. = FALSE) + + unknown_args <- names[!(names %in% args)] + if (length(unknown_args) > 0) + stop(paste("Unknown argument in model:", unknown_args), call. = FALSE) + + + if (x$dist == "vonMises") { + if (!is(x$kappa, "numeric")) + stop("kappa must be single non-negative numeric value.", call. = FALSE) + + if (length(x$kappa) != 1) + stop("kappa must be single non-negative numeric value.", call. = FALSE) + + if (!is.finite(x$kappa)) + stop("kappa must be single non-negative numeric value.", call. = FALSE) + + if (x$kappa < 0) + stop("kappa must be single non-negative numeric value.", call. = FALSE) + } else { + stop(paste("Invalid distribution name:", x$dist), call. = FALSE) + } +} + +#' Validate transition args for SSF +#' +#' Validates the model for the samc() function +#' +#' @param x A list +#' @noRd +.validate_ssf <- function(x, method) { + names <- names(x) + + args = c("name", "fun", "dir", "sym", "ssc") + methods = c("direct", "iter") + + missing_args <- args[!(args %in% names)] + if (length(missing_args) > 0) + stop(paste("Missing argument in model:", missing_args), call. = FALSE) + + if (!(is(x$fun, "function") || is(x$fun, "character"))) { + stop("'fun' must be a supported named function or a user defined function") + } else if (!(x$dir %in% c(4, 8))) { + stop("`dir` must be set to either 4 or 8", call. = FALSE) + } else if (!is(x$sym, "logical")) { + stop("`sym` must be set to either TRUE or FALSE", call. = FALSE) + } + + if (!(method %in% methods)) + stop("Invalid method for model", call. = FALSE) + + unknown_args <- names[!(names %in% args)] + if (length(unknown_args) > 0) + stop(paste("Unknown argument in model:", unknown_args), call. = FALSE) + + if (!is(x$ssc, "numeric")) + stop("ssc must be single numeric value.", call. = FALSE) + + if (length(x$ssc) != 1) + stop("ssc must be single numeric value.", call. = FALSE) + + if (!is.finite(x$ssc)) + stop("ssc must be single numeric value.", call. = FALSE) +} + + diff --git a/R/visitation.R b/R/visitation.R index 59bb2fe..380ee5e 100644 --- a/R/visitation.R +++ b/R/visitation.R @@ -1,5 +1,5 @@ -# Copyright (c) 2019-2023 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. #' @include samc-class.R location-class.R NULL @@ -168,6 +168,16 @@ setMethod( res <- res + q2 } + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + res = diag(pv) %*% res + + res = apply(res, 1, function(x) samc:::.summarize_crw(samc, x, sum)) + res = apply(res, 1, function(x) samc:::.summarize_crw(samc, x, sum)) # Same margin because results of last are transposed + } + return(res) }) @@ -177,29 +187,18 @@ setMethod( "visitation", signature(samc = "samc", init = "missing", origin = "location", dest = "missing", time = "numeric"), function(samc, origin, time){ - .disable_conv(samc) if (is(origin, "matrix")) { if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) } else { - if (length(origin) != 1) - stop("origin can only contain a single value for this version of the function", call. = FALSE) + if (length(origin) != 1) stop("origin can only contain a single value for this version of the function", call. = FALSE) } - - origin = .process_locations(samc, origin) .validate_time_steps(time) - q = samc$q_matrix - - time = c(1, time) - - ft = .sum_qpow_row(q, origin, time) + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) - if (length(ft) == 1) { - return(ft[[1]]) - } else { - return(ft) - } + return(visitation(samc, init, time = time)) }) # visitation(samc, dest, time) ---- @@ -209,7 +208,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "numeric"), function(samc, dest, time){ .disable_conv(samc) - .disable_crw(samc) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) @@ -221,7 +219,25 @@ setMethod( time = c(1, time) - ft = .sum_qpow_col(q, dest, time) + if (samc@model$name == "RW") { + vec = numeric(samc@nodes) + vec[dest] = 1 + } else if (samc@model$name == "CRW") { + vec = as.numeric(samc@crw_map[,1] == dest) + } else { + stop("Unexpected model", call. = FALSE) + } + + ft = .sum_qpow_col(q, vec, time) + + ft = lapply(ft, as.vector) + + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + ft = lapply(ft, function(x) .summarize_crw(samc, pv * x, sum)) + } if (length(ft) == 1) { return(ft[[1]]) @@ -237,7 +253,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "numeric"), function(samc, origin, dest, time){ .disable_conv(samc) - .disable_crw(samc) dest = .process_locations(samc, dest) @@ -258,20 +273,21 @@ setMethod( "visitation", signature(samc = "samc", init = "ANY", origin = "missing", dest = "missing", time = "numeric"), function(samc, init, time){ - .disable_crw(samc) - .validate_time_steps(time) check(samc, init) pv <- .process_init(samc, init) - if (samc@solver %in% c("direct", "iter")) { q <- samc$q_matrix time <- c(1, time) - ft <- .sum_psiqpow(q, pv, time) + ft <- .sum_qpow_row(q, pv, time) + + ft = lapply(ft, as.vector) + + if (samc@model$name == "CRW") ft = lapply(ft, function(x) .summarize_crw(samc, x, sum)) if (length(ft) == 1) { return(ft[[1]]) @@ -279,8 +295,6 @@ setMethod( return(ft) } } else if (samc@solver == "conv") { - - results_list = samc:::.convolution_short(time, samc@conv_cache, pv, samc@threads) res = as.vector(results_list$vis[[1]]) @@ -303,8 +317,20 @@ setMethod( if (!samc@override) stop("This version of the visitation() method produces a large dense matrix.\nSee the documentation for details.", call. = FALSE) - n <- Matrix::solve(samc@data@f) - return(as.matrix(n)) + n = Matrix::solve(samc@data@f) + n = as.matrix(n) + + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + n = diag(pv) %*% n + + n = apply(n, 1, function(x) samc:::.summarize_crw(samc, x, sum)) + n = apply(n, 1, function(x) samc:::.summarize_crw(samc, x, sum)) # Same margin because results of last are transposed + } + + return(n) }) # visitation(samc, origin) ---- @@ -313,7 +339,6 @@ setMethod( "visitation", signature(samc = "samc", init = "missing", origin = "location", dest = "missing", time = "missing"), function(samc, origin){ - .disable_conv(samc) if (is(origin, "matrix")) { if (nrow(origin) > 1) stop("Only a single origin is supported for CRW", call. = FALSE) @@ -322,17 +347,10 @@ setMethod( stop("origin can only contain a single value for this version of the function", call. = FALSE) } - origin = .process_locations(samc, origin) + init = .map_location(samc, origin) - if (samc@solver == "iter") { - r <- .f_row_iter(samc@data@f, origin) - } else { - r <- .f_row(samc@data@f, origin, samc@.cache$sc) - } - - - return(as.vector(r)) + return(visitation(samc, init = init)) }) # visitation(samc, dest) ---- @@ -342,7 +360,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "missing", dest = "location", time = "missing"), function(samc, dest){ .disable_conv(samc) - .disable_crw(samc) if (is.matrix(dest)) { @@ -351,15 +368,31 @@ setMethod( stop("dest can only contain a single location for this version of the function", call. = FALSE) } - dest <- .process_locations(samc, dest) + dest = .process_locations(samc, dest) + + if (samc@model$name == "RW") { + vec = numeric(samc@nodes) + vec[dest] = 1 + } else if (samc@model$name == "CRW") { + vec = as.numeric(samc@crw_map[,1] == dest) + } else { + stop("Unexpected model", call. = FALSE) + } if (samc@solver == "iter") { - r <- .f_col_iter(samc@data@f, dest); + r = .f_col_iter(samc@data@f, vec) } else { - r <- .f_col(samc@data@f, dest, samc@.cache$sc); + r = .f_col(samc@data@f, vec, samc@.cache$sc) + } + + if (samc@model$name == "CRW") { + pv = samc@prob_mat + pv = pv[!is.na(pv)] + + r = .summarize_crw(samc, pv * r, sum) } - return(as.vector(r)) + return(r) }) # visitation(samc, origin, dest) ---- @@ -369,7 +402,6 @@ setMethod( signature(samc = "samc", init = "missing", origin = "location", dest = "location", time = "missing"), function(samc, origin, dest){ .disable_conv(samc) - .disable_crw(samc) origin <- .process_locations(samc, origin) dest <- .process_locations(samc, dest) @@ -395,18 +427,21 @@ setMethod( signature(samc = "samc", init = "ANY", origin = "missing", dest = "missing", time = "missing"), function(samc, init){ check(samc, init) - .disable_crw(samc) pv <- .process_init(samc, init) if (samc@solver %in% c("direct", "iter")) { if (samc@solver == "iter") { - r <- .psif_iter(samc@data@f, pv) + r <- .f_row_iter(samc@data@f, pv) } else { - r <- .psif(samc@data@f, pv, samc@.cache$sc) + r <- .f_row(samc@data@f, pv, samc@.cache$sc) } - return(as.vector(r)) + r = as.vector(r) + + if (samc@model$name == "CRW") r = .summarize_crw(samc, r, sum) + + return(r) } else if (samc@solver == "conv") { results_list = samc:::.convolution_long(samc@conv_cache, pv, samc@threads) @@ -424,16 +459,13 @@ setMethod( "visitation", signature(samc = "samc", init = "ANY", origin = "missing", dest = "location", time = "missing"), function(samc, init, dest){ - .disable_crw(samc) .disable_conv(samc) - check(samc, init) - - pv <- .process_init(samc, init) + dest = .process_locations(samc, dest) - fj <- visitation(samc, dest = dest) + vis = visitation(samc, init) - return(as.numeric(pv %*% fj)) + return(vis[dest]) }) @@ -468,18 +500,45 @@ setMethod( "visitation_net", signature(samc = "samc", init = "missing", origin = "location", dest = "location"), function(samc, origin, dest) { + .disable_crw(samc) if (length(origin) != 1) stop("origin can only contain a single location for this version of the function", call. = FALSE) if (length(dest) != 1) stop("dest can only contain a single location for this version of the function", call. = FALSE) - vis = visitation(samc, origin = origin) + origin = .process_locations(samc, origin) + init = .map_location(samc, origin) + + check(samc, init) + + pv <- .process_init(samc, init) + + if (samc@solver %in% c("direct", "iter")) { + if (samc@solver == "iter") { + r <- .f_row_iter(samc@data@f, pv) + } else { + r <- .f_row(samc@data@f, pv, samc@.cache$sc) + } + + r = as.vector(r) + + # if (samc@model$name == "CRW") r = .summarize_crw(samc, r, sum) + + vis = r + } else if (samc@solver == "conv") { + + results_list = samc:::.convolution_long(samc@conv_cache, pv, samc@threads) + + vis = results_list$vis + } else { + stop("Invalid method attribute in samc object.") + } - vq = vis*samc$q_matrix + vq = vis * samc@data@f n_net = abs(Matrix::skewpart(vq)) - visit_net = pmax(Matrix::rowSums(n_net), Matrix::colSums(n_net)) + visit_net = as.vector(Matrix::colSums(n_net)) visit_net[c(origin, dest)] = 2 * visit_net[c(origin, dest)] return(visit_net) diff --git a/R/zzz.R b/R/zzz.R index a63c226..7bc6289 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -1,3 +1,5 @@ +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. # .onLoad <- function(libname, pkgname) { # assign("samc_env", new.env(parent = emptyenv()), parent.env()) diff --git a/docs/404.html b/docs/404.html index 9fb589f..107d7e9 100644 --- a/docs/404.html +++ b/docs/404.html @@ -6,7 +6,7 @@ Page not found (404) • samc - + @@ -32,7 +32,7 @@ samc - 3.2.1 + 3.3.0 @@ -181,7 +181,7 @@

Page not found (404)

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/LICENSE-text.html b/docs/LICENSE-text.html index bffc717..d13fb3e 100644 --- a/docs/LICENSE-text.html +++ b/docs/LICENSE-text.html @@ -1,5 +1,5 @@ -License • samcLicense • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -131,8 +131,8 @@

License

-
                    GNU GENERAL PUBLIC LICENSE
-                       Version 3, 29 June 2007
+
                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
 
  Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  Everyone is permitted to copy and distribute verbatim copies
@@ -140,17 +140,15 @@ 

License

Preamble - The GNU General Public License is a free, copyleft license for -software and other kinds of works. + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. 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 +our General Public Licenses are 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. +software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you @@ -159,44 +157,34 @@

License

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. + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. The precise terms and conditions for copying, distribution and modification follow. @@ -205,7 +193,7 @@

License

0. Definitions. - "This License" refers to version 3 of the GNU General Public License. + "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. @@ -682,35 +670,45 @@

License

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. + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. 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 +under version 3 of the GNU 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. +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. 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 +the GNU Affero 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 +Program specifies that a certain numbered version of the GNU Affero 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 +GNU Affero 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 +versions of the GNU Affero 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. @@ -765,47 +763,36 @@

License

the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> - Copyright (C) <year> <name of author> + + Copyright (C) {{ year }} {{ organization }} 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 + it under the terms of the GNU Affero 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. + GNU Affero General Public License for more details. - You should have received a copy of the GNU General Public License + You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. 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: - - <program> Copyright (C) <year> <name of author> - 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". + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. 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 +For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>. - - 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 -<http://www.gnu.org/philosophy/why-not-lgpl.html>. -
@@ -823,7 +810,7 @@

License

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/LICENSE.html b/docs/LICENSE.html new file mode 100644 index 0000000..1ca10e3 --- /dev/null +++ b/docs/LICENSE.html @@ -0,0 +1,350 @@ + +GNU Affero General Public License • samc + + +
+
+ + + +
+
+ + +
+ +

Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>

+

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

+
+

Preamble

+

The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.

+

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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.

+

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.

+

Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.

+

A secondary benefit of defending all users’ freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.

+

The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.

+

An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.

+

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 Affero 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.

+
+
+ +

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:

+
    1. The work must carry prominent notices stating that you modified it, and giving a relevant date.
    2. +
  • +
    1. 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”.
    2. +
  • +
    1. 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.
    2. +
  • +
    1. 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.
    2. +
  • +

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:

+
    1. 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.
    2. +
  • +
    1. 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.
    2. +
  • +
    1. 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.
    2. +
  • +
    1. 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.
    2. +
  • +
    1. 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.
    2. +
  • +

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:

+
    1. Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
    2. +
  • +
    1. 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
    2. +
  • +
    1. 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
    2. +
  • +
    1. Limiting the use for publicity purposes of names of licensors or authors of the material; or
    2. +
  • +
    1. Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
    2. +
  • +
    1. 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.
    2. +
  • +

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. Remote Network Interaction; Use with the GNU General Public License.

+

Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.

+

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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License.

+
+
+

14. Revised Versions of this License.

+

The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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.

+
    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+

Also add information on how to contact you by electronic and paper mail.

+

If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a “Source” link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.

+

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 AGPL, see https://www.gnu.org/licenses/.

+
+
+ +
+ + + +
+ + + +
+ +
+

Site built with pkgdown 2.0.9.

+
+ +
+ + + + + + + + diff --git a/docs/articles/article-circuit-theory.html b/docs/articles/article-circuit-theory.html index 7ef3cda..b3eff5e 100644 --- a/docs/articles/article-circuit-theory.html +++ b/docs/articles/article-circuit-theory.html @@ -6,7 +6,7 @@ Circuit Theory • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0 @@ -163,7 +163,7 @@

Circuit Theory

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/article-circuit-theory.Rmd @@ -216,7 +216,7 @@

Code Setup
-library("terra")
+library("terra")
 library("raster")
 library("gdistance")
 library("samc")
@@ -242,10 +242,10 @@ 

Code Setupres_data = samc::rasterize(res_data) abs_data = samc::rasterize(abs_data) -plot(res_data, main = "Example Resistance Data", xlab = "x", ylab = "y", col = viridis(256)) -plot(abs_data, main = "Example Absorption Data", xlab = "x", ylab = "y", col = viridis(256)) +plot(res_data, main = "Example Resistance Data", xlab = "x", ylab = "y", col = viridis(256)) +plot(abs_data, main = "Example Absorption Data", xlab = "x", ylab = "y", col = viridis(256)) -rw_model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE) +rw_model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE) samc_obj = samc(res_data, abs_data, model = rw_model) @@ -303,14 +303,14 @@

Commute Time and Hitting Time
 # Absorption only at the origin i
 abs_data_i = res_data * 0
-abs_data_i[cellFromXY(res_data, origin_coords)] = 1
-plot(abs_data_i, main = "Source Absorption Map", col = viridis(256))
+abs_data_i[cellFromXY(res_data, origin_coords)] = 1
+plot(abs_data_i, main = "Source Absorption Map", col = viridis(256))
 
 
 # Absorption only at the destination j
 abs_data_j = res_data * 0
-abs_data_j[cellFromXY(res_data, dest_coords)] = 1
-plot(abs_data_j, main = "Destination Absorption Map", col = viridis(256))
+abs_data_j[cellFromXY(res_data, dest_coords)] = 1 +plot(abs_data_j, main = "Destination Absorption Map", col = viridis(256))

 # Create samc objects for each direction
@@ -322,12 +322,15 @@ 

Commute Time and Hitting Timehitting_ji = survival(samc_ji, abs_data_j) # Reusing the other abs layer as an occupancy input hitting_ij -#> [1] 210.222 -hitting_ji -#> [1] 293.0998 -hitting_ij + hitting_ji -#> [1] 503.3218 - +#> [1] 210.222

+
+hitting_ji
+#> [1] 293.0998
+
+hitting_ij + hitting_ji
+#> [1] 503.3218
+
+
 # Calculate commute distance with gdistance
 commuteDistance(gdist, rbind(origin_coords, dest_coords))
 #>          1
@@ -362,30 +365,34 @@ 

Commute Time and Hitting Timesurvival() function, the result of cond_passage() does not include the extra absorption time step; it only calculates the time to reach the destination.

-
+
 hitting_ij_cp = cond_passage(samc_ij, origin = origin_cell, dest = dest_cell)
 hitting_ji_cp = cond_passage(samc_ji, origin = dest_cell, dest = origin_cell)
 
 hitting_ij_cp
-#> [1] 209.222
-hitting_ji_cp
-#> [1] 292.0998
-hitting_ij_cp + hitting_ji_cp
+#> [1] 209.222
+
+hitting_ji_cp
+#> [1] 292.0998
+
+hitting_ij_cp + hitting_ji_cp
 #> [1] 501.3218

More importantly, this is just a special case where we demonstrate the relationship between circuit theory and SAMC. For more generic scenarios, only a single normal samc object is required for calculating the hitting times:

-
+
 # Calculate hitting times and commute distance for the original absorption data
 reg_hitting_ij = cond_passage(samc_obj, origin = origin_cell, dest = dest_cell)
 reg_hitting_ji = cond_passage(samc_obj, origin = dest_cell, dest = origin_cell)
 
 reg_hitting_ij
-#> [1] 128.2726
-reg_hitting_ji
-#> [1] 127.6531
-reg_hitting_ij + reg_hitting_ji
+#> [1] 128.2726
+
+reg_hitting_ji
+#> [1] 127.6531
+
+reg_hitting_ij + reg_hitting_ji
 #> [1] 255.9258

In this case, the resulting commute distance is much lower because absorption occurs throughout the landscape. In the simplified scenario, @@ -433,35 +440,36 @@

Net and Total Movement Flowvisitation_net() function. To get equivalent results between gdistance and SAMC, we must again disregard absorption outside the destination.

-
+
 # Total movement flow with gdistance
 total_gdist = passage(gdist, origin_coords, dest_coords, theta = 0, totalNet = "total")
-plot(total_gdist, main = "Total Movement Flow (gdistance)", col = viridis(256))
+plot(total_gdist, main = "Total Movement Flow (gdistance)", col = viridis(256))
 
 # Equivalent total movement flow with SAMC
 total_samc = visitation(samc_ij, origin = origin_cell)
 total_samc_ras = map(samc_ij, total_samc)
-plot(total_samc_ras, main = "Total Movement Flow (samc)", col = viridis(256))
+plot(total_samc_ras, main = "Total Movement Flow (samc)", col = viridis(256))
 
 # Verify that they have the same values
-all.equal(values(total_gdist), values(total_samc_ras))
+all.equal(values(total_gdist), values(total_samc_ras))
 #> [1] "Attributes: < target is NULL, current is list >"
-#> [2] "target is numeric, current is matrix"
-
+#> [2] "target is numeric, current is matrix"
+
+
 
 
 # Net movement flow with gdistance
 net_gdist = passage(gdist, origin_coords, dest_coords, theta = 0, totalNet = "net")
-net_gdist = rast(net_gdist)
-plot(net_gdist, main = "Net Movement Flow (gdistance)", col = viridis(256))
+net_gdist = rast(net_gdist)
+plot(net_gdist, main = "Net Movement Flow (gdistance)", col = viridis(256))
 
 # Equivalent net movement flow with SAMC
 net_samc = visitation_net(samc_ij, origin = origin_cell, dest = dest_cell)
 net_samc_ras = map(samc_obj, net_samc)
-plot(net_samc_ras,  main = "Net Movement Flow (samc)", col = viridis(256))
+plot(net_samc_ras,  main = "Net Movement Flow (samc)", col = viridis(256))
 
 # Verify that they have the same values
-all.equal(values(net_gdist), values(net_samc_ras))
+all.equal(values(net_gdist), values(net_samc_ras))
 #> [1] "Attributes: < Component \"dimnames\": Component 2: 1 string mismatch >"

As with commute distance, SAMC is not limited to calculating the @@ -469,10 +477,10 @@

Net and Total Movement Flowvisitation() and visitation_net() are perfectly valid for our original samc object with broader landscape absorption.

-
+
 reg_net_samc = visitation_net(samc_obj, origin = origin_cell, dest = dest_cell)
 reg_samc_ras = map(samc_obj, reg_net_samc)
-plot(reg_samc_ras,  main = "Net Movement Flow (samc with absorption)", col = viridis(256))
+plot(reg_samc_ras, main = "Net Movement Flow (samc with absorption)", col = viridis(256))

Overall, incorporating absorption more broadly has reduced the net movement flow because a portion of the individuals is now being removed @@ -481,19 +489,20 @@

Net and Total Movement Flow
-plot(net_gdist - reg_samc_ras, main = "Effect of Absorption on Net Movement Flow", col = viridis(256))

+
+plot(net_gdist - reg_samc_ras, main = "Effect of Absorption on Net Movement Flow", col = viridis(256))

This shows a nearly imperceptible effect of the absorption layer on the net movement flow below the strip of absorption, but as individuals encounter absorption, the net movement flow in the top half of the map drops dramatically. We can see that the presence of the absorption strip has decreased the net movement flow at the destination over 97%:

-
+
 net_samc_ras[dest_cell] # Net movement flow at destination w/o absorption
 #>   lyr.1
-#> 1     1
-reg_net_samc[dest_cell] # With absorption
+#> 1     1
+
+reg_net_samc[dest_cell] # With absorption
 #> [1] 0.02681907

@@ -515,7 +524,7 @@

Net and Total Movement Flow

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-1.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-1.png index 8de26f6..41283cd 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-1.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-1.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-2.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-2.png index fed75d3..c86493b 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-2.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-1-2.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-1.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-1.png index da47a2e..e49c108 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-1.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-1.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-2.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-2.png index a3c3419..ca4d657 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-2.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-2-2.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-2.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-2.png index b27fb64..19ee8e4 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-2.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-2.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-3.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-3.png index e3d3ab6..ba1965a 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-3.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-3.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-4.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-4.png index 8072df9..42b5f52 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-4.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-6-4.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-7-1.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-7-1.png index ee5fa61..ca894e0 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-7-1.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-7-1.png differ diff --git a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-8-1.png b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-8-1.png index b57a8f6..17c5017 100644 Binary files a/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-8-1.png and b/docs/articles/article-circuit-theory_files/figure-html/unnamed-chunk-8-1.png differ diff --git a/docs/articles/article-computation-methods.html b/docs/articles/article-computation-methods.html index 176e65a..0729572 100644 --- a/docs/articles/article-computation-methods.html +++ b/docs/articles/article-computation-methods.html @@ -6,7 +6,7 @@ Computation Methods • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Computation Methods

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/article-computation-methods.Rmd @@ -267,9 +267,6 @@

ConvolutionCompatibility Tables

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/article-models.html b/docs/articles/article-models.html index 4fcd003..8484986 100644 --- a/docs/articles/article-models.html +++ b/docs/articles/article-models.html @@ -6,7 +6,7 @@ Models • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0 @@ -163,7 +163,7 @@

Models

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/article-models.Rmd @@ -175,19 +175,18 @@

2023-05-12

Background

-

The samc package currently supports two different models: random-walk -(RW) and correlated random-walk (CRW). The random-walk is the default -model that always has been used by the package. Version 3 made breaking -changes to the samc() function to setup a structure for specifying -different models, and the correlated random-walk model is the first -alternative to make use of this starting with version 3.1.

+

The samc package currently supports a random-walk (RW) model. The +random-walk is the default model that always has been used by the +package. Version 3 made breaking changes to the samc() function to setup +a structure for specifying different models, with plans for a correlated +random-walk model in the future.

Models

Models in the samc package are defined as a list with various components depending on the context:

-
list(name, fun, dir, sym, dist, kappa)
+
list(name, fun, dir, sym)

Random-Walk

@@ -211,104 +210,32 @@

Random-Walk -

Correlated Random-Walk -

-

The correlated random-walk features are currently experimental. -They may not work in all situations and are subject to change.

-

The correlated random-walk uses the same properties as the RW:

-
    -
  • -name: must be set to "CRW" -
  • -
  • -fun: a function for calculating transition -probabilities from the data input.
  • -
  • -dir can be either 4 or 8 -
  • -
  • -sym can be either TRUE or -FALSE, and is used as an optimization when calculating -transition probabilities.
  • -
-

To describe the correlated random-walk behavior, additional -parameters are needed to describe the turning behavior:

-
    -
  • -dist specifies the name of a distribution or function. -Currently, only "vonMises" is supported.
  • -
  • -kappa is specific to the von Mises distribution. It is -a single number greater than or equal to 0 that sets a -global turning probability.
  • -
-

As the capabilities of the correlated random-walk are expanded in -future updates, additional options will be documented here.

-

To run metrics using the CRW, a single origin and direction value -must be supplied in a 1x2 matrix (subject to change). The direction is -an integer in the range 1-8 with the directions illustrated as -follows:

-
1 2 3
-4   5
-6 7 8
-

For example, 1 is up and left, while 6 is -down and left.

-

Support for multiple origin values, init -maps, and dest values is not currently implemented, but -will be available future releases once the CRW implementation details -are finalized.

-

Examples

-
-library("terra")
+
+library("terra")
 library("samc")
 library("viridisLite")
 
 res_data <- samc::rasterize(example_toy_res)
 abs_data <- samc::rasterize(example_toy_res * 0 + 0.05)
 
-plot(res_data, main = "Resistance")
+plot(res_data, main = "Resistance")
 
 rw_model <- list(fun = "1/mean(x)", dir = 8, sym = TRUE)
-crw_model0 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 0) # Effectively a random walk after the first step
-crw_model1 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 1) # Some bias against turning
-crw_model2 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 2) # Moderate bias against turning
-crw_model8 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 8) # Very strong bias against turning
 
 samc_rw <- samc(res_data, abs_data, model = rw_model)
-samc_crw0 <- samc(res_data, abs_data, model = crw_model0)
-#> Warning in samc(data, absorption, fidelity, model, options = options): CRW
-#> support is currently experimental and may see input changes
-samc_crw1 <- samc(res_data, abs_data, model = crw_model1)
-#> Warning in samc(data, absorption, fidelity, model, options = options): CRW
-#> support is currently experimental and may see input changes
-samc_crw2 <- samc(res_data, abs_data, model = crw_model2)
-#> Warning in samc(data, absorption, fidelity, model, options = options): CRW
-#> support is currently experimental and may see input changes
-samc_crw8 <- samc(res_data, abs_data, model = crw_model8)
-#> Warning in samc(data, absorption, fidelity, model, options = options): CRW
-#> support is currently experimental and may see input changes
 
 origin = 85 # Centered near the bottom
 dir = 1 # Up and left
 
 vis_rw <- as.vector(visitation(samc_rw, origin = origin))
-vis_crw0 <- as.vector(visitation(samc_crw0, origin = matrix(c(origin, dir), 1)))
-vis_crw1 <- as.vector(visitation(samc_crw1, origin = matrix(c(origin, dir), 1)))
-vis_crw2 <- as.vector(visitation(samc_crw2, origin = matrix(c(origin, dir), 1)))
-vis_crw8 <- as.vector(visitation(samc_crw8, origin = matrix(c(origin, dir), 1)))
-
 
-plot(map(samc_rw, vis_rw), col = viridis(1024), main = "RW")
-plot(map(samc_crw0, vis_crw0), col = viridis(1024), main = "CRW (kappa=0)")
-plot(map(samc_crw1, vis_crw1), col = viridis(1024), main = "CRW (kappa=1)")
-plot(map(samc_crw2, vis_crw2), col = viridis(1024), main = "CRW (kappa=2)")
-plot(map(samc_crw8, vis_crw8), col = viridis(1024), main = "CRW (kappa=8)")
-

+# The RW results +plot(map(samc_rw, vis_rw), col = viridis(1024), main = "RW")
+

@@ -329,7 +256,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/article-models_files/figure-html/unnamed-chunk-1-1.png b/docs/articles/article-models_files/figure-html/unnamed-chunk-1-1.png index 161d8b1..a2a926c 100644 Binary files a/docs/articles/article-models_files/figure-html/unnamed-chunk-1-1.png and b/docs/articles/article-models_files/figure-html/unnamed-chunk-1-1.png differ diff --git a/docs/articles/article-models_files/figure-html/unnamed-chunk-1-2.png b/docs/articles/article-models_files/figure-html/unnamed-chunk-1-2.png index 94e1f0d..4fc3945 100644 Binary files a/docs/articles/article-models_files/figure-html/unnamed-chunk-1-2.png and b/docs/articles/article-models_files/figure-html/unnamed-chunk-1-2.png differ diff --git a/docs/articles/code-snippets.html b/docs/articles/code-snippets.html index 1cd52db..45b2cda 100644 --- a/docs/articles/code-snippets.html +++ b/docs/articles/code-snippets.html @@ -6,7 +6,7 @@ Code Snippets • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0 @@ -163,7 +163,7 @@

Code Snippets

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/code-snippets.Rmd @@ -189,7 +189,7 @@

Reshaping output from pairwise()df <- pairwise(...) # Use reshape2 to convert to a pairwise matrix -reshape2::acast(df, origin ~ dest, value.var = "result")

+reshape2::acast(df, origin ~ dest, value.var = "result") @@ -210,7 +210,7 @@

Reshaping output from pairwise()

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/data-disconnected.html b/docs/articles/data-disconnected.html index 94b4884..e439dd6 100644 --- a/docs/articles/data-disconnected.html +++ b/docs/articles/data-disconnected.html @@ -6,7 +6,7 @@ Disconnected Data • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0 @@ -163,7 +163,7 @@

Disconnected Data

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/data-disconnected.Rmd @@ -199,9 +199,9 @@

RastersNA values to the same value, like 1. Then turn all the NA’s to a different value, like 0. Then plot it. Code:

-
raster[!is.na(raster[])) <- 1 
-raster[is.na(raster[])) <- 0
-plot(raster)
+
raster[!is.na(raster[])) <- 1 
+raster[is.na(raster[])) <- 0
+plot(raster)

If your raster is particularly large, then you might need to save it to a high-res image to spot solo pixels in an external picture editor or viewer.

@@ -225,7 +225,7 @@

Rasters

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/example-coinflip.html b/docs/articles/example-coinflip.html index 7141c8d..fc1ac8e 100644 --- a/docs/articles/example-coinflip.html +++ b/docs/articles/example-coinflip.html @@ -6,7 +6,7 @@ Coin Flip • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0 @@ -163,7 +163,7 @@

Coin Flip

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/example-coinflip.Rmd @@ -311,8 +311,9 @@

Metrics# Given a starting point (in this case, a sequence of 3 flips), how many times # would we expect the different combinations of 3 flips to occur before absorption? visitation(samc_obj, origin = "HHT") -#> [1] 1.5 0.5 0.5 0.5 1.0 1.0 1.0 - +#> [1] 1.5 0.5 0.5 0.5 1.0 1.0 1.0 +
+
 sum(visitation(samc_obj, origin = "HHT")) # Compare to survival() result
 #> [1] 6

In this case, we specify a starting sequence of \(HHT\), which is one flip away from \(HTH\) (absorption). As an example @@ -326,12 +327,13 @@

Metrics -
+
 # Instead of a start point, we can look at an endpoint and how often we expect
 # it to occur for each of the possible starting points
 visitation(samc_obj, dest = "THT")
-#> [1] 0.5 0.5 1.5 0.5 1.0 1.0 1.0
-
+#> [1] 0.5 0.5 1.5 0.5 1.0 1.0 1.0
+
+
 # These results are just rows/cols of a larger matrix. We can get the entire matrix
 # of the start/end possibilities but first, we have to disable some safety measures
 # in place because this package is designed to work with extremely large P matrices
@@ -346,8 +348,9 @@ 

Metrics#> [4,] 1.5 1.5 0.5 1.5 1 1 1 #> [5,] 1.0 1.0 1.0 1.0 3 2 1 #> [6,] 1.0 1.0 1.0 1.0 1 2 1 -#> [7,] 1.0 1.0 1.0 1.0 2 2 2 - +#> [7,] 1.0 1.0 1.0 1.0 2 2 2

+
+
 rowSums(visitation(samc_obj)) # equivalent to survival() above
 #> [1]  6  8  6  8 10  8 10

A third relevant metric is dispersal(). Rather than the @@ -356,9 +359,9 @@

Metrics\(HTH\). The short-term variant can be used to specify a limit to the number of flips we will make.

-
+
 dispersal(samc_obj, dest = "TTT", time = 5)
-#> [1] 0.28125 0.21875 0.28125 0.21875      NA 0.21875 0.59375
+#> [1] 0.28125 0.21875 0.28125 0.21875 0.00000 0.21875 0.59375

In this case, we’re trying to find the probability of \(TTT\) occurring within 5 flips. The results show the probability for every possible starting sequencing. For example, the seventh element, \(HTT\) @@ -384,7 +387,7 @@

Metrics

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/example-maze-part1.html b/docs/articles/example-maze-part1.html index a45c9e3..4239774 100644 --- a/docs/articles/example-maze-part1.html +++ b/docs/articles/example-maze-part1.html @@ -6,7 +6,7 @@ Maze Part 1 • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0 @@ -163,7 +163,7 @@

Maze Part 1

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/example-maze-part1.Rmd @@ -189,7 +189,7 @@

Libraries
 library(raster)
-library(terra)
+library(terra)
 library(gdistance)
 library(samc)
 library(viridisLite)
@@ -202,11 +202,11 @@

Setup
 plot_maze <- function(map, title, colors) {
   # start = 1 (top left), finish = last element (bottom right)
-  sf <- terra::xyFromCell(map, c(1, ncell(map)))
+  sf <- terra::xyFromCell(map, c(1, ncell(map)))
 
   plot(map, main = title, col = colors, axes = FALSE, asp = 1)
-  plot(as.polygons(map, dissolve = FALSE), border = 'black', lwd = 1, add = TRUE)
-  points(sf, pch = c('S', 'F'), cex = 1, font = 2)
+  plot(as.polygons(map, dissolve = FALSE), border = 'black', lwd = 1, add = TRUE)
+  points(sf, pch = c('S', 'F'), cex = 1, font = 2)
 }

Create a simple color palette for when only one or two colors are needed in a figure:

@@ -225,19 +225,18 @@

Setup # Get info about the shortest path through the maze using gdistance lcd <- (function() { - points <- xyFromCell(maze_res, c(1, 400)) + points <- xyFromCell(maze_res, c(1, 400)) - tr <- transition(raster(maze_res), function(x) 1/mean(x), 4) + tr <- transition(raster(maze_res), function(x) 1/mean(x), 4) tr <- geoCorrection(tr) list(dist = gdistance::costDistance(tr, points), path = shortestPath(tr, points[1, ], points[2, ], output="SpatialLines")) })() -#> as(<dsCMatrix>, "dgTMatrix") is deprecated since Matrix 1.5-0; do as(as(., "generalMatrix"), "TsparseMatrix") instead # Basic maze layout plot_maze(maze_res, "Resistance", vir_col[1]) -lines(lcd$path, col = vir_col[2], lw = 3) +lines(lcd$path, col = vir_col[2], lw = 3)

Create an absorption map where the finish point is the only source of absorption. It will have an absorption value of 1.0, which @@ -254,11 +253,11 @@

Setup package, it’s sometimes possible for floating point precision issues to arise where equality comparisons between two decimal values don’t yield the expected results. It’s an unfortunate limitation of all computer -hardware and is why functions like all.equal() exist in +hardware and is why functions like all.equal() exist in base R. Unfortunately, there isn’t a base function available for the specific comparisons we want to perform, so we will manually have to do it. To do so, we will need a tolerance value and will use the default -tolerance used by all.equal():

+tolerance used by all.equal():

 tolerance = sqrt(.Machine$double.eps) # Default tolerance in functions like all.equal()
 
@@ -271,7 +270,7 @@ 

Create the samc object
-rw_model <- list(fun = function(x) 1/mean(x), dir = 4, sym = TRUE)
+rw_model <- list(fun = function(x) 1/mean(x), dir = 4, sym = TRUE)
 
 maze_samc <- samc(maze_res, maze_finish, model = rw_model)
 
@@ -287,7 +286,7 @@ 

Create the samc objectlocate() function. It’s important to remember -that the results from xyFromCell() (used above for the +that the results from xyFromCell() (used above for the RasterLayer object) do NOT work for samc objects. Although the results from both functions may be equivalent in certain cases, they generally will not be equivalent and cannot be used interchangeably.

@@ -350,18 +349,18 @@

Probability of visiting a celldispersal() function:

-
maze_disp <- dispersal(maze_samc, origin = maze_origin)
-#> 
-#> Cached diagonal not found.
-#> Performing setup. This can take several minutes... Complete.
-#> Calculating matrix inverse diagonal...
-#> 
-Computing: 100% (done)                         
-#> 
-Complete                                                      
-#> Diagonal has been cached. Continuing with metric calculation...
-
-plot_maze(map(maze_samc, maze_disp), "Probability of Visit", viridis(256))
+
+maze_disp <- dispersal(maze_samc, origin = maze_origin)
+#> 
+#> Cached diagonal not found.
+#> Performing setup. This can take several minutes... Complete.
+#> Calculating matrix inverse diagonal...
+#> Computing: 100% (done)                         
+#> Complete                                                      
+#> Diagonal has been cached. Continuing with metric calculation...
+
+
+plot_maze(map(maze_samc, maze_disp), "Probability of Visit", viridis(256))

To complete the maze, the individual has to visit every cell along the path to the exit, so all of those cells will have a probability of @@ -377,7 +376,7 @@

Probability of visiting a cell function can be used to identify the route through the maze:

-
+
 # Ideally would use `as.numeric(maze_disp == 1)`, but floating point precision issues force an approximation
 maze_disp_sol <- as.numeric(abs(maze_disp - 1) < tolerance)
 
@@ -388,7 +387,7 @@ 

Probability of visiting a cell

The package can be used to see how many times each cell in the maze is expected to be visited on average. This is done using the visitation() metric:

-
+
 maze_visit <- visitation(maze_samc, origin = maze_origin)
 
 plot_maze(map(maze_samc, maze_visit), "Visits Per Cell", viridis(256))

Since the finish point leads to total absorption, it will only be visited once:

-
+
 maze_visit[maze_dest]
 #> [1] 1
@@ -414,14 +413,14 @@

Expected locationdistribution() function, the location of an individual in the maze can be predicted for a given time:

-
+
 maze_dist <- distribution(maze_samc, origin = maze_origin, time = 20)
 
 plot_maze(map(maze_samc, maze_dist), "Location at t=20", col = viridis(256))

There’s an odd pattern here that can be emphasized by incrementing the time from 20 to 21:

-
+
 maze_dist <- distribution(maze_samc, origin = maze_origin, time = 21)
 
 plot_maze(map(maze_samc, maze_dist), "Location at t=21", viridis(256))
@@ -455,7 +454,7 @@

Occupancy
+
 maze_init <- maze_res * 0
 maze_init[1, 1] <- 1
 
@@ -463,15 +462,16 @@ 

Occupancy

Using the survival() metric, it produces the same result as before:

-
+
 survival(maze_samc, init = maze_init)
-#> [1] 13869
-
+#> [1] 13869
+
+
 maze_surv[maze_origin]
 #> [1] 13869

But now, more interesting scenarios can be tested. For example, let’s start the maze with 3 individuals:

-
+
 # Scenario 1: 3 people start in the maze
 maze_init3 <- maze_res * 0
 maze_init3[1, 1] <- 3
@@ -484,12 +484,12 @@ 

Occupancy
+
 survival(maze_samc, init = maze_init3) / 3
 #> [1] 13869

Here’s a different scenario with 3 individuals again, but now they start in different corners of the maze:

-
+
 # Scenario 2: A person starts in each corner of the maze
 maze_init3 <- maze_res * 0
 maze_init3[1, 1] <- 1
@@ -504,7 +504,7 @@ 

Occupancy
+
 survival(maze_samc, init = maze_init3) / 3
 #> [1] 7316.333

This is because the additional individuals are now located in corners @@ -513,7 +513,7 @@

Occupancy
+
 maze_init3_dist <- distribution(maze_samc, init = maze_init3, time = 17)
 
 # This makes it easier to see how far along the individuals could be
@@ -555,7 +555,7 @@ 

Future parts

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-11-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-11-1.png index 2730170..a707262 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-11-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-11-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-12-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-12-1.png index e726e89..1079926 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-12-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-12-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-14-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-14-1.png index 76b0f2a..f2e28f5 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-14-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-14-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-16-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-16-1.png index 2122f78..6d12ad8 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-16-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-16-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-17-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-17-1.png index a1eac77..4419ece 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-17-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-17-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-18-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-18-1.png index 0c520de..ca7becc 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-18-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-18-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-22-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-22-1.png index f1b2c07..97a0160 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-22-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-22-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-24-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-24-1.png index c5d8fe2..1f91f2d 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-24-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-24-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-4-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-4-1.png index 81c1f9f..e763c85 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-4-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-4-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-5-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-5-1.png index 9c7b286..b5ec889 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-5-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-5-1.png differ diff --git a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-8-1.png b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-8-1.png index 86967fe..a58b0cc 100644 Binary files a/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-8-1.png and b/docs/articles/example-maze-part1_files/figure-html/unnamed-chunk-8-1.png differ diff --git a/docs/articles/example-maze-part2.html b/docs/articles/example-maze-part2.html index dfc3451..277dd28 100644 --- a/docs/articles/example-maze-part2.html +++ b/docs/articles/example-maze-part2.html @@ -6,7 +6,7 @@ Maze Part 2 • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Maze Part 2

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/example-maze-part2.Rmd @@ -207,7 +207,7 @@

Fidelity
 # Intersections determined using a moving window function
-ints_res <- focal(maze_res,
+ints_res <- focal(maze_res,
                   w = matrix(c(NA, 1, NA, 1, 1, 1, NA, 1, NA), nrow = 3, ncol = 3),
                   fun = function(x) {sum(!is.na(x)) > 3})
 
@@ -226,14 +226,17 @@ 

Fidelity
 # Original results from Part 1
 survival(maze_samc)[maze_origin]
-#> [1] 13869
-cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
-#> [1] 13868
-
+#> [1] 13869

+
+cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 13868
+
+
 # Results with fidelity at intersections
 survival(ints_samc)[maze_origin]
-#> [1] 14356
-cond_passage(ints_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 14356
+
+cond_passage(ints_samc, origin = maze_origin, dest = maze_dest)
 #> [1] 14355

Intuitively, with “hesitation” added to the movement, the expected time to finish increases. Also, note that incorporating fidelity in this @@ -241,27 +244,28 @@

Fidelitysurvival() and cond_passage().

In terms of the probability of visiting any particular cell, changing the fidelity does not change the results from Part 1:

-
ints_disp <- dispersal(ints_samc, origin = maze_origin)
-#> 
-#> Cached diagonal not found.
-#> Performing setup. This can take several minutes... Complete.
-#> Calculating matrix inverse diagonal...
-#> 
-Computing: 100% (done)                         
-#> 
-Complete                                                      
-#> Diagonal has been cached. Continuing with metric calculation...
-
-all.equal(maze_disp, ints_disp)
-#> [1] TRUE
+
+ints_disp <- dispersal(ints_samc, origin = maze_origin)
+#> 
+#> Cached diagonal not found.
+#> Performing setup. This can take several minutes... Complete.
+#> Calculating matrix inverse diagonal...
+#> Computing: 100% (done)                         
+#> Complete                                                      
+#> Diagonal has been cached. Continuing with metric calculation...
+
+
+all.equal(maze_disp, ints_disp)
+#> [1] TRUE

Fidelity does, however, change the number of times each cell is expected to be visited:

-
+
 ints_visit <- visitation(ints_samc, origin = maze_origin)
 
-all.equal(maze_visit, ints_visit)
-#> [1] "Mean relative difference: 0.03511428"
-
+all.equal(maze_visit, ints_visit)
+#> [1] "Mean relative difference: 0.03511428"
+
+
 # Let's plot the difference to see if there is a noticeable pattern
 visit_diff <- map(maze_samc, ints_visit) - map(maze_samc, maze_visit)
 plot_maze(visit_diff, "Visits Per Cell (Difference)", viridis(256))
@@ -276,7 +280,7 @@

Fidelity0.0) experienced no change. Let’s check these ideas:

-
+
 # First, let's see which cells changed.
 # Ideally would just use `visit_diff > 0`, but floating point precision issues force an approximation
 plot_maze(visit_diff > tolerance, "Visits With Non-Zero Difference", vir_col)
@@ -300,7 +304,7 @@ 

Fidelitydistribution() metric. Recall from Part 1 that there was an alternating pattern with the cells when changing the time steps. With fidelity, this effect still exists, but not to the same degree:

-
+
 ints_dist <- distribution(ints_samc, origin = maze_origin, time = 20)
 plot_maze(map(ints_samc, ints_dist), "Location at t=20", viridis(256))
 
@@ -310,7 +314,7 @@ 

FidelityGiven a sufficient amount of time, the cumulative effect of having fidelity present will almost entirely eliminate this pattern. Even from time steps 200-201, the alternating pattern is visually nearly gone:

-
+
 ints_dist <- distribution(ints_samc, origin = maze_origin, time = 200)
 plot_maze(map(ints_samc, ints_dist), "Location at t=200", viridis(256))
 
@@ -319,7 +323,7 @@ 

Fidelity

For comparison, here’s the original samc object using the same time steps:

-
+
 maze_dist <- distribution(maze_samc, origin = maze_origin, time = 200)
 plot_maze(map(maze_samc, maze_dist), "Location at t=200", viridis(256))
 
@@ -340,9 +344,9 @@ 

Dead-End Avoidance
+
 # Dead ends
-ends_res <- focal(maze_res,
+ends_res <- focal(maze_res,
                   w = matrix(c(NA, 1, NA, 1, 1, 1, NA, 1, NA), nrow = 3, ncol = 3),
                   fun = function(x){sum(!is.na(x)) == 2})
 ends_res[is.na(maze_res)] <- NA
@@ -357,40 +361,43 @@ 

Dead-End Avoidance
+
 ends_samc <- samc(ends_res, maze_finish, model = rw_model)

Hypothetically, since an individual can now “look ahead”, they should be able to get through the maze faster because they are spending less time in dead ends. This is easily verified:

-
+
 # Original results from Part 1
 survival(maze_samc)[maze_origin]
-#> [1] 13869
-cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
-#> [1] 13868
-
+#> [1] 13869
+
+cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 13868
+
+
 # Results with dead ends
 survival(ends_samc)[maze_origin]
-#> [1] 11313
-cond_passage(ends_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 11313
+
+cond_passage(ends_samc, origin = maze_origin, dest = maze_dest)
 #> [1] 11312

Since the dead ends have a lower probability of being transitioned to, the dispersal() and visitation() metrics should reflect that:

-
ends_disp <- dispersal(ends_samc, origin = maze_origin)
-#> 
-#> Cached diagonal not found.
-#> Performing setup. This can take several minutes... Complete.
-#> Calculating matrix inverse diagonal...
-#> 
-Computing: 100% (done)                         
-#> 
-Complete                                                      
-#> Diagonal has been cached. Continuing with metric calculation...
-plot_maze(map(maze_samc, ends_disp), "Probability of Visit", viridis(256))
-
-ends_visit <- visitation(ends_samc, origin = maze_origin)
-plot_maze(map(maze_samc, ends_visit), "Visits Per Cell", viridis(256))
+
+ends_disp <- dispersal(ends_samc, origin = maze_origin)
+#> 
+#> Cached diagonal not found.
+#> Performing setup. This can take several minutes... Complete.
+#> Calculating matrix inverse diagonal...
+#> Computing: 100% (done)                         
+#> Complete                                                      
+#> Diagonal has been cached. Continuing with metric calculation...
+
+plot_maze(map(maze_samc, ends_disp), "Probability of Visit", viridis(256))
+
+ends_visit <- visitation(ends_samc, origin = maze_origin)
+plot_maze(map(maze_samc, ends_visit), "Visits Per Cell", viridis(256))

The effect is more obvious with the expected number of visits from visitation(); the probability illustration is more subtle @@ -424,7 +431,7 @@

Traps has already been created for the finish point. A second simple absorption component will be created that represents a few traps with a 0.2 or 20% absorption probability:

-
+
 # Traps absorption layer
 maze_traps <- maze_res * 0
 maze_traps[17, 3] <- 0.2
@@ -435,7 +442,7 @@ 

Traps

Since the total absorption is the sum of these two components, the samc object will have to be recreated:

-
+
 maze_abs_total <- maze_finish + maze_traps
 
 traps_samc <- samc(maze_res, maze_abs_total, model = rw_model)
@@ -443,17 +450,20 @@

Traps original example from Part 1. Continuing the previous strategy, let’s start with determining how long it is expected for an individual to finish the maze:

-
+
 # Original results from Part 1
 survival(maze_samc)[maze_origin]
-#> [1] 13869
-cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
-#> [1] 13868
-
+#> [1] 13869
+
+cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 13868
+
+
 # Results with traps
 survival(traps_samc)[maze_origin]
-#> [1] 1330.26
-cond_passage(traps_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 1330.26
+
+cond_passage(traps_samc, origin = maze_origin, dest = maze_dest)
 #> [1] 3060.207

The results are drastically different from what has been seen before. First, the clear relationship between survival() and @@ -465,7 +475,7 @@

Traps drastically changes the plotting results of survival() (note the change in figure title from Part 1 to reflect the new interpretation):

-
+
 traps_surv <- survival(traps_samc)
 
 # Note the updated title from part 1
@@ -473,20 +483,20 @@ 

Traps

The results are also drastically different from Part 1 when looking at visitation probability and the number of visits:

-
traps_disp <- dispersal(traps_samc, origin = maze_origin)
-#> 
-#> Cached diagonal not found.
-#> Performing setup. This can take several minutes... Complete.
-#> Calculating matrix inverse diagonal...
-#> 
-Computing: 100% (done)                         
-#> 
-Complete                                                      
-#> Diagonal has been cached. Continuing with metric calculation...
-plot_maze(map(traps_samc, traps_disp), "Probability of Visit", viridis(256))
-
-traps_visit <- visitation(traps_samc, origin = maze_origin)
-plot_maze(map(traps_samc, traps_visit), "Visits Per Cell", viridis(256))
+
+traps_disp <- dispersal(traps_samc, origin = maze_origin)
+#> 
+#> Cached diagonal not found.
+#> Performing setup. This can take several minutes... Complete.
+#> Calculating matrix inverse diagonal...
+#> Computing: 100% (done)                         
+#> Complete                                                      
+#> Diagonal has been cached. Continuing with metric calculation...
+
+plot_maze(map(traps_samc, traps_disp), "Probability of Visit", viridis(256))
+
+traps_visit <- visitation(traps_samc, origin = maze_origin)
+plot_maze(map(traps_samc, traps_visit), "Visits Per Cell", viridis(256))

Importantly, the technique in Part 1 of using visitation probabilities of 1.0 to identify the route through the maze @@ -496,7 +506,7 @@

Traps finish, which in turn means the probability of visiting the finish is now less than 1.0. However, the same technique can be used to see something interesting:

-
+
 # Ideally, we would just use `as.numeric(traps_disp == 1)`, but we have floating point precision issues here, so we will approximate it
 traps_disp_route <- as.numeric(abs(traps_disp - 1) < tolerance)
 
@@ -513,7 +523,7 @@ 

Additional metricsmortality(), it is possible to visualize where an individual is expected to be absorbed:

-
+
 traps_mort <- mortality(traps_samc, origin = maze_origin)
 
 plot_maze(map(traps_samc, traps_mort), "Absorption Probability", viridis(256))
@@ -521,10 +531,11 @@

Additional metrics
+
 traps_mort[traps_mort > 0]
-#> [1] 0.852084306 0.113761093 0.003940915 0.030213685
-
+#> [1] 0.852084306 0.113761093 0.003940915 0.030213685
+
+
 traps_mort[maze_dest]
 #> [1] 0.03021369

There’s only a 3.0% chance of an individual finishing the maze! This @@ -542,31 +553,32 @@

Additional metrics
+
 # Naming the rasters will make things easier and less prone to user error later
-names(maze_finish) <- "Finish"
-names(maze_traps) <- "Traps"
+names(maze_finish) <- "Finish"
+names(maze_traps) <- "Traps"
 
 traps_samc$abs_states <- c(maze_finish, maze_traps)

By doing so, the mortality() metric now returns a list with information about not just the total absorption, but the individual components as well. This allows the role of different types of absorption to be individually accessed and visualized:

-
+
 traps_mort_dec <- mortality(traps_samc, origin = maze_origin)
 
 str(traps_mort_dec)
 #> List of 3
 #>  $ total : num [1:215] 0 0 0 0 0.852 ...
 #>  $ Finish: num [1:215] 0 0 0 0 0 0 0 0 0 0 ...
-#>  $ Traps : num [1:215] 0 0 0 0 0.852 ...
-
+#>  $ Traps : num [1:215] 0 0 0 0 0.852 ...
+
+
 plot_maze(map(traps_samc, traps_mort_dec$Finish), "Absorption Probability (Finish)", viridis(256))
 plot_maze(map(traps_samc, traps_mort_dec$Traps), "Absorption Probability (Traps)", viridis(256))

With multiple sources of absorption now specified in the samc object, the absorption() metric becomes relevant:

-
+
 absorption(traps_samc, origin = maze_origin)
 #>     Finish      Traps 
 #> 0.03021369 0.96978631
@@ -608,7 +620,7 @@

Part 3

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-1.png index 6b38fcf..cd969e7 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-2.png index 4e7fdd6..b99d46b 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-2.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-3.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-3.png index 40587a1..8828191 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-3.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-3.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-4.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-4.png index e8d3896..edeba77 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-4.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-4.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-5.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-5.png index 524a0a5..e335bc9 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-5.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-1-5.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-1.png index 3f68c7c..d4893de 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-2.png index 84572ab..6158986 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-10-2.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-11-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-11-1.png index 86cd16f..cc65856 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-11-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-11-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-1.png index 65532c7..adb31d6 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-2.png index 797c64e..4502a35 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-14-2.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-15-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-15-1.png index 81e6d39..2dcd8e7 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-15-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-15-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-18-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-18-1.png index ab3146f..c21002e 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-18-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-18-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-1.png index 2653d2c..ce43503 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-2.png index 8377ac0..ca25485 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-19-2.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-2-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-2-1.png index 4b97a74..24a4f30 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-2-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-2-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-20-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-20-1.png index e509372..a29c7b6 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-20-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-20-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-21-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-21-1.png index 0adadb3..74f12a5 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-21-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-21-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-1.png index 51963ec..5e720f9 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-2.png index 880c602..b3eada9 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-24-2.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-6-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-6-1.png index fbd2d3c..2d7ec2a 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-6-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-6-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-7-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-7-1.png index 74dbc43..c85cd3b 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-7-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-7-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-1.png index fab7a4b..7a7d33e 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-2.png index e4d2f57..e08869f 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-8-2.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-1.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-1.png index c831368..2c1ee68 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-1.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-1.png differ diff --git a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-2.png b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-2.png index eeef13d..5ea2af0 100644 Binary files a/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-2.png and b/docs/articles/example-maze-part2_files/figure-html/unnamed-chunk-9-2.png differ diff --git a/docs/articles/example-maze-part3.html b/docs/articles/example-maze-part3.html index 872add4..eeddffd 100644 --- a/docs/articles/example-maze-part3.html +++ b/docs/articles/example-maze-part3.html @@ -6,7 +6,7 @@ Maze Part 3 • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Maze Part 3

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/example-maze-part3.Rmd @@ -205,9 +205,9 @@

Shortcut # Get info about the shortest path through the new maze using gdistance lcd2 <- (function() { - points <- xyFromCell(short_res, c(1, 400)) + points <- xyFromCell(short_res, c(1, 400)) - tr <- transition(raster(short_res), function(x) 1/mean(x), 4) + tr <- transition(raster(short_res), function(x) 1/mean(x), 4) tr <- geoCorrection(tr) list(dist = gdistance::costDistance(tr, points), @@ -216,7 +216,7 @@

Shortcut plot_maze(short_res, "Shortcut Maze", vir_col) -lines(lcd2$path, col = vir_col[2], lw = 3)

+lines(lcd2$path, col = vir_col[2], lw = 3)

Use gdistance to quickly verify the change in distance for the shortest solution:

@@ -259,8 +259,9 @@

Shortcut
 # Expected time to finish from the start
 short_surv[maze_origin]
-#> [1] 9022.974
-
+#> [1] 9022.974

+
+
 # The difference from our original maze
 short_surv[maze_origin] - maze_surv[maze_origin]
 #> [1] -4846.026
@@ -278,31 +279,31 @@

Shortcutsurvival() and cond_passage(). Since this example is back to a single absorbing state at the finish point, this relationship is restored:

-
+
 short_cond <- cond_passage(short_samc, dest = short_dest)
 short_cond[maze_origin]
 #> [1] 9021.974

Part 2 also showed that including additional absorbing states affects the probability of cells being visited. Modifying the maze to have multiple routes also has significant ramifications:

-
short_disp <- dispersal(short_samc, origin = short_origin)
-#> 
-#> Cached diagonal not found.
-#> Performing setup. This can take several minutes... Complete.
-#> Calculating matrix inverse diagonal...
-#> 
-Computing: 100% (done)                         
-#> 
-Complete                                                      
-#> Diagonal has been cached. Continuing with metric calculation...
-
-plot_maze(map(short_samc, short_disp), "Probability of Visit (Shortcut Maze)", viridis(256))
+
+short_disp <- dispersal(short_samc, origin = short_origin)
+#> 
+#> Cached diagonal not found.
+#> Performing setup. This can take several minutes... Complete.
+#> Calculating matrix inverse diagonal...
+#> Computing: 100% (done)                         
+#> Complete                                                      
+#> Diagonal has been cached. Continuing with metric calculation...
+
+
+plot_maze(map(short_samc, short_disp), "Probability of Visit (Shortcut Maze)", viridis(256))

Notably, it is again no longer possible to discern the optimal route through the maze by looking for cells with a probability of 1.0. But, like Part 2, a partial path can still be identified:

-
+
 # Ideally, we would just use `as.numeric(short_disp == 1)`, but we have floating point precision issues here, so we will approximate it
 short_disp_sol <- as.numeric(abs(short_disp - 1) < tolerance)
 
@@ -318,7 +319,7 @@ 

Combined Example -
+
 # Combine our previous resistance layers
 all_res <- max(c(short_res, ints_res, ends_res), na.rm = TRUE)
 
@@ -345,7 +346,7 @@ 

Combined Example

Create the new samc object:

-
+
 all_samc <- samc(all_res, all_abs_total, model = rw_model)
 
 # We can actually reuse the short_res locations in this case, but let's make new ones anyway
@@ -353,7 +354,7 @@ 

Combined Exampleall_finish <- locate(all_samc, data.frame(x = 20, y = 1))

Following the previous model changes, start by looking at the expected time to absorption:

-
+
 all_surv <- survival(all_samc)
 
 # Note the updated title from part 1
@@ -367,29 +368,36 @@ 

Combined Example

Next is a complete overview of the different results for survival() and cond_passage():

-
+
 # Original results (Part 1)
 survival(maze_samc)[maze_origin]
-#> [1] 13869
-cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
-#> [1] 13868
-
+#> [1] 13869
+
+cond_passage(maze_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 13868
+
+
 # Results with traps (Part 2)
 survival(traps_samc)[maze_origin]
-#> [1] 1330.26
-cond_passage(traps_samc, origin = maze_origin, dest = maze_dest)
-#> [1] 3060.207
-
+#> [1] 1330.26
+
+cond_passage(traps_samc, origin = maze_origin, dest = maze_dest)
+#> [1] 3060.207
+
+
 # Results with a shortcut
 survival(short_samc)[short_origin]
-#> [1] 9022.974
-cond_passage(short_samc, origin = short_origin, dest = short_dest)
-#> [1] 9021.974
-
+#> [1] 9022.974
+
+cond_passage(short_samc, origin = short_origin, dest = short_dest)
+#> [1] 9021.974
+
+
 # Results with everything
 survival(all_samc)[all_start]
-#> [1] 968.4007
-cond_passage(all_samc, origin = all_start, dest = all_finish)
+#> [1] 968.4007
+
+cond_passage(all_samc, origin = all_start, dest = all_finish)
 #> [1] 2000.364

The presence of both the traps and the shortcut has a cumulative effect on both metrics; the time to absorption decreases, as does the @@ -399,10 +407,11 @@

Combined Examplemortality() metric shows how introducing the shortcut affects the probability of finishing the maze vs being absorbed in the traps:

-
+
 traps_mort[traps_mort > 0]
-#> [1] 0.852084306 0.113761093 0.003940915 0.030213685
-
+#> [1] 0.852084306 0.113761093 0.003940915 0.030213685
+
+
 all_mort <- mortality(all_samc, origin = all_start)
 all_mort[all_mort > 0]
 #> [1] 0.81665446 0.08106988 0.05073905 0.05153661
@@ -453,7 +462,7 @@

Future Work

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-1.png index 6b38fcf..cd969e7 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-1.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-2.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-2.png index 4e7fdd6..b99d46b 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-2.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-2.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-3.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-3.png index 40587a1..8828191 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-3.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-3.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-4.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-4.png index 3cdc495..3583122 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-4.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-4.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-5.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-5.png index 7999d50..10bf32c 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-5.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-5.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-6.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-6.png index 2b55e6d..272290c 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-6.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-6.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-7.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-7.png index 31d88b1..cc58ce1 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-7.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-1-7.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-10-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-10-1.png index 2d97331..7fa8175 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-10-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-10-1.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-1.png index 91ffc76..1c94c74 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-1.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-2.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-2.png index f5aa2c3..6062c43 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-2.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-11-2.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-13-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-13-1.png index 1e5139e..7807bbd 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-13-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-13-1.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-2-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-2-1.png index 94d7956..6933abe 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-2-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-2-1.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-6-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-6-1.png index 2d6778a..103c025 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-6-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-6-1.png differ diff --git a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-9-1.png b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-9-1.png index b0bbe66..5b16fcd 100644 Binary files a/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-9-1.png and b/docs/articles/example-maze-part3_files/figure-html/unnamed-chunk-9-1.png differ diff --git a/docs/articles/index.html b/docs/articles/index.html index d861532..1bb30f8 100644 --- a/docs/articles/index.html +++ b/docs/articles/index.html @@ -1,5 +1,5 @@ -Articles • samcArticles • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0

@@ -183,7 +183,7 @@

All vignettes

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/overview.html b/docs/articles/overview.html index 65edbaa..ca6cbec 100644 --- a/docs/articles/overview.html +++ b/docs/articles/overview.html @@ -6,7 +6,7 @@ Overview • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0
@@ -163,7 +163,7 @@

Overview

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/overview.Rmd @@ -321,8 +321,8 @@

Utility Functionslocate() function is used to get cell numbers for use as origin and dest values in various analytical function arguments. This function should be used instead of -cellFromXY() in the raster or terra packages because -cellFromXY() cell numbers do not necessarily correspond to +cellFromXY() in the raster or terra packages because +cellFromXY() cell numbers do not necessarily correspond to cell numbers in the samc package (the samc package does not assign cell numbers to NA cells, whereas other packages do). The locate() function can be used to return a map with the cell @@ -541,10 +541,6 @@

Built-in Example Data
 str(samc::example_split_corridor)
-#> List of 3
-#>  $ res : num [1:34, 1:202] NA NA NA NA NA NA NA NA NA NA ...
-#>  $ abs : num [1:34, 1:202] NA NA NA NA NA NA NA NA NA NA ...
-#>  $ init: num [1:34, 1:202] NA NA NA NA NA NA NA NA NA NA ...
 
 res_data <- samc::example_split_corridor$res
 abs_data <- samc::example_split_corridor$abs
@@ -553,7 +549,6 @@ 

Built-in Example Dataplot(rasterize(res_data), main = "Example Resistance Data", xlab = "x", ylab = "y", col = viridis(256)) plot(rasterize(abs_data), main = "Example Absorption Data", xlab = "x", ylab = "y", col = viridis(256)) plot(rasterize(init_data), main = "Example Starting Location Data", xlab = "x", ylab = "y", col = viridis(256))

-

@@ -574,7 +569,7 @@

Built-in Example Data

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/parallel.html b/docs/articles/parallel.html index cf76d65..ad21dd6 100644 --- a/docs/articles/parallel.html +++ b/docs/articles/parallel.html @@ -6,7 +6,7 @@ Parallel Computing • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0
@@ -163,7 +163,7 @@

Parallel Computing

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/parallel.Rmd @@ -263,7 +263,7 @@

Limitations

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/performance.html b/docs/articles/performance.html index 7624721..a5bab14 100644 --- a/docs/articles/performance.html +++ b/docs/articles/performance.html @@ -6,7 +6,7 @@ Performance • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Performance

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/performance.Rmd @@ -394,7 +394,7 @@

Temporal Memory Usage

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/troubleshooting.html b/docs/articles/troubleshooting.html index 5d09c2c..cac5c25 100644 --- a/docs/articles/troubleshooting.html +++ b/docs/articles/troubleshooting.html @@ -6,7 +6,7 @@ Troubleshooting • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0
@@ -163,7 +163,7 @@

Troubleshooting

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/troubleshooting.Rmd @@ -195,8 +195,9 @@

Error in raster::compareRasterr1 <- res_data r2 <- res_data check(r1, r2) -#> [1] TRUE - +#> [1] TRUE

+
+
 
 # Remove the NA's in r2 by overwriting all the elements with the number 1.
 # check() doesn't check the actual values of the data, but it does check the
@@ -205,8 +206,9 @@ 

Error in raster::compareRasterr2 <- res_data r2[1] <- 1 check(r1, r2) -#> Error: NA mismatch in input data - +#> Error: NA mismatch in input data

+
+
 
 # Change the dimensions of r2 by subsetting it. check() ensures that the data
 # inputs have the same number of rows and columns
@@ -231,27 +233,29 @@ 

Unable to find an inherited methodnumeric when the function expects a RasterLayer or a matrix).

-
+
 # Example: Skipping optional arguments. In this case, the `fidelity` argument is
 # optional, so we skip it. The model argument, however, is always required, 
 # so we pass the relevant to it. But because we don't specify which
 # argument it is, R is trying to find a version of the function that expects it
 # as the third argument, but this version does not exist.
-samc_obj <- samc(res_data, abs_data, list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
-#> Error in (function (classes, fdef, mtable) : unable to find an inherited method for function 'samc' for signature '"matrix", "matrix", "list", "missing"'
-
+samc_obj <- samc(res_data, abs_data, list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
+#> Error: unable to find an inherited method for function 'samc' for signature 'data = "matrix", absorption = "matrix", fidelity = "list", model = "missing"'
+
+
 # Solution
-samc_obj <- samc(res_data, abs_data, model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
+samc_obj <- samc(res_data, abs_data, model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
 
 
 # Example: Incorrect input types. In this case, we are attempting to pass a
 # single numeric value as absorption data. However, the absorption data must 
 # always be in a matrix or RasterLayer object
-samc_obj <- samc(res_data, 0.01, model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
-#> Error in (function (classes, fdef, mtable) : unable to find an inherited method for function 'samc' for signature '"matrix", "numeric", "missing", "list"'
-
+samc_obj <- samc(res_data, 0.01, model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
+#> Error: unable to find an inherited method for function 'samc' for signature 'data = "matrix", absorption = "numeric", fidelity = "missing", model = "list"'
+
+
 # Solution
-samc_obj <- samc(res_data, abs_data, model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))
+samc_obj <- samc(res_data, abs_data, model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE))

Error: All disconnected regions must have at least one non-zero @@ -294,7 +298,7 @@

Err

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/tutorial-animations.html b/docs/articles/tutorial-animations.html index 0ec5701..db10d19 100644 --- a/docs/articles/tutorial-animations.html +++ b/docs/articles/tutorial-animations.html @@ -6,7 +6,7 @@ Animations • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Animations

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/tutorial-animations.Rmd @@ -197,7 +197,7 @@

Setup library("raster") library("ggplot2") library("viridisLite") -library("gifski") +library("gifski") library("gganimate") @@ -209,7 +209,7 @@

Setup # Setup the details for our transition function -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -275,7 +275,7 @@

Using gganimate coord_equal() + theme_bw() -animate(anim, duration = 5, height = 2, width = 6, units = "in", res = 150)

+animate(anim, duration = 5, height = 2, width = 6, units = "in", res = 150)

@@ -297,7 +297,7 @@

Using gganimate

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/tutorial-basic.html b/docs/articles/tutorial-basic.html index 20389de..99e8690 100644 --- a/docs/articles/tutorial-basic.html +++ b/docs/articles/tutorial-basic.html @@ -6,7 +6,7 @@ Basic Tutorial • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Basic Tutorial

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/tutorial-basic.Rmd @@ -186,7 +186,7 @@

Libraries
 # First step is to load the libraries. Not all of these libraries are stricly
 # needed; some are used for convenience and visualization for this tutorial.
-library("terra")
+library("terra")
 library("samc")
 library("viridisLite")

@@ -214,9 +214,9 @@

Load the Data# the default extents will be (0,1) for both x and y, which is not only # uninformative, but can result in "stretching" when visualizing datasets # based non-square matrices. -plot(res_data, main = "Example Resistance Data", xlab = "x", ylab = "y", col = viridis(256)) -plot(abs_data, main = "Example Absorption Data", xlab = "x", ylab = "y", col = viridis(256)) -plot(init_data, main = "Example Occupancy Data", xlab = "x", ylab = "y", col = viridis(256))

+plot(res_data, main = "Example Resistance Data", xlab = "x", ylab = "y", col = viridis(256)) +plot(abs_data, main = "Example Absorption Data", xlab = "x", ylab = "y", col = viridis(256)) +plot(init_data, main = "Example Occupancy Data", xlab = "x", ylab = "y", col = viridis(256))

@@ -224,7 +224,7 @@

Create the samc Object
 # Setup the details for our transition function
-rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities
+rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities
                  dir = 8, # Directions of the transitions. Either 4 or 8.
                  sym = TRUE) # Is the function symmetric?
 
@@ -240,7 +240,7 @@ 

Create the samc Object# cells in your data +1. In this case, our data has 2624 non-NA cells, so the # matrix should be 2625 x 2625 str(samc_obj) -#> Formal class 'samc' [package "samc"] with 12 slots +#> Formal class 'samc' [package "samc"] with 14 slots #> ..@ data :Formal class 'samc_data' [package "samc"] with 3 slots #> .. .. ..@ f :Formal class 'dgCMatrix' [package "Matrix"] with 6 slots #> .. .. .. .. ..@ i : int [1:21612] 0 1 115 116 117 0 1 2 116 117 ... @@ -257,41 +257,41 @@

Create the samc Object#> ..@ model :List of 4 #> .. ..$ fun :function (x) #> .. .. ..- attr(*, "srcref")= 'srcref' int [1:8] 2 24 2 44 24 44 2 2 -#> .. .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x563e5451e848> +#> .. .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x55b489390810> #> .. ..$ dir : num 8 #> .. ..$ sym : logi TRUE #> .. ..$ name: chr "RW" #> ..@ source : chr "SpatRaster" +#> ..@ nodes : int 2624 #> ..@ map :S4 class 'SpatRaster' [package "terra"] #> ..@ crw_map : NULL +#> ..@ prob_mat : NULL #> ..@ names : NULL #> ..@ clumps : int 1 #> ..@ override : logi FALSE #> ..@ solver : chr "direct" #> ..@ threads : num 1 -#> ..@ .cache :<environment: 0x563e581ebb90>

+#> ..@ .cache :<environment: 0x55b48f5a4f50>

Basic Analysis

-
# Convert the initial state data to probabilities
-init_prob_data <- init_data / sum(values(init_data), na.rm = TRUE)
-
-
-# Calculate short- and long-term mortality metrics and long-term dispersal
-short_mort <- mortality(samc_obj, init_prob_data, time = 4800)
-long_mort <- mortality(samc_obj, init_prob_data)
-long_disp <- dispersal(samc_obj, init_prob_data)
-#> 
-#> Cached diagonal not found.
-#> Performing setup. This can take several minutes... Complete.
-#> Calculating matrix inverse diagonal...
-#> 
-Computing: 50%  (~10s remaining)       
-Computing: 100% (done)                         
-#> 
-Complete                                                      
-#> Diagonal has been cached. Continuing with metric calculation...
+
+# Convert the initial state data to probabilities
+init_prob_data <- init_data / sum(values(init_data), na.rm = TRUE)
+
+
+# Calculate short- and long-term mortality metrics and long-term dispersal
+short_mort <- mortality(samc_obj, init_prob_data, time = 4800)
+long_mort <- mortality(samc_obj, init_prob_data)
+long_disp <- dispersal(samc_obj, init_prob_data)
+#> 
+#> Cached diagonal not found.
+#> Performing setup. This can take several minutes... Complete.
+#> Calculating matrix inverse diagonal...
+#> Computing: 100% (done)                         
+#> Complete                                                      
+#> Diagonal has been cached. Continuing with metric calculation...

Visualization @@ -304,9 +304,9 @@

Visualization# Plot the mortality and dispersal results -plot(short_mort_map, main = "Short-term Mortality", xlab = "x", ylab = "y", col = viridis(256)) -plot(long_mort_map, main = "Long-term Mortality", xlab = "x", ylab = "y", col = viridis(256)) -plot(long_disp_map, main = "Long-term Dispersal", xlab = "x", ylab = "y", col = viridis(256))

+plot(short_mort_map, main = "Short-term Mortality", xlab = "x", ylab = "y", col = viridis(256)) +plot(long_mort_map, main = "Long-term Mortality", xlab = "x", ylab = "y", col = viridis(256)) +plot(long_disp_map, main = "Long-term Dispersal", xlab = "x", ylab = "y", col = viridis(256))

@@ -328,7 +328,7 @@

Visualization

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-1.png b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-1.png index 7b22880..f26b082 100644 Binary files a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-1.png and b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-1.png differ diff --git a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-2.png b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-2.png index f46c2ae..67e1362 100644 Binary files a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-2.png and b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-2.png differ diff --git a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-3.png b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-3.png index 0cf1972..a0be1ef 100644 Binary files a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-3.png and b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-2-3.png differ diff --git a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-1.png b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-1.png index 0eacce1..0b8f04d 100644 Binary files a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-1.png and b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-1.png differ diff --git a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-2.png b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-2.png index 3f27d49..312aa35 100644 Binary files a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-2.png and b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-2.png differ diff --git a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-3.png b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-3.png index ec6cd67..fa37ef8 100644 Binary files a/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-3.png and b/docs/articles/tutorial-basic_files/figure-html/unnamed-chunk-5-3.png differ diff --git a/docs/articles/tutorial-ggplot.html b/docs/articles/tutorial-ggplot.html index 65ac706..9d92dd8 100644 --- a/docs/articles/tutorial-ggplot.html +++ b/docs/articles/tutorial-ggplot.html @@ -6,7 +6,7 @@ ggplot Visualization • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

ggplot Visualization

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/tutorial-ggplot.Rmd @@ -184,7 +184,7 @@

Setup
 # First step is to load the libraries. Not all of these libraries are stricly
 # needed; some are used for convenience and visualization for this tutorial.
-library("terra")
+library("terra")
 library("samc")
 library("ggplot2")
 
@@ -203,7 +203,7 @@ 

Setup # Setup the details for our transition function -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -214,7 +214,7 @@

Setup # Convert the initial state data to probabilities -init_prob_data <- init_data / sum(values(init_data), na.rm = TRUE) +init_prob_data <- init_data / sum(values(init_data), na.rm = TRUE) # Calculate short- and long-term mortality metrics and long-term dispersal @@ -233,9 +233,9 @@

Visualization With ggplot2
 # Convert the landscape data to RasterLayer objects, then to data frames for ggplot
-res_df <- as.data.frame(res_data, xy = TRUE, na.rm = TRUE)
-abs_df <- as.data.frame(abs_data, xy = TRUE, na.rm = TRUE)
-init_df <- as.data.frame(init_data, xy = TRUE, na.rm = TRUE)
+res_df <- as.data.frame(res_data, xy = TRUE, na.rm = TRUE)
+abs_df <- as.data.frame(abs_data, xy = TRUE, na.rm = TRUE)
+init_df <- as.data.frame(init_data, xy = TRUE, na.rm = TRUE)
 
 
 # When overlaying the patch raster, we don't want to plot cells with values of 0
@@ -262,9 +262,9 @@ 

Visualization With ggplot2

 # Convert result RasterLayer objects to data frames for ggplot
-short_mort_df <- as.data.frame(short_mort_map, xy = TRUE, na.rm = TRUE)
-long_mort_df <- as.data.frame(long_mort_map, xy = TRUE, na.rm = TRUE)
-long_disp_df <- as.data.frame(long_disp_map, xy = TRUE, na.rm = TRUE)
+short_mort_df <- as.data.frame(short_mort_map, xy = TRUE, na.rm = TRUE)
+long_mort_df <- as.data.frame(long_mort_map, xy = TRUE, na.rm = TRUE)
+long_disp_df <- as.data.frame(long_disp_map, xy = TRUE, na.rm = TRUE)
 
 
 # Plot short-term mortality
@@ -316,7 +316,7 @@ 

Visualization With ggplot2

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/tutorial-locations.html b/docs/articles/tutorial-locations.html index 9b9137e..cae0600 100644 --- a/docs/articles/tutorial-locations.html +++ b/docs/articles/tutorial-locations.html @@ -6,7 +6,7 @@ Locations • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Locations

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/tutorial-locations.Rmd @@ -222,7 +222,7 @@

Setup
 # First step is to load the libraries. Not all of these libraries are strictly
 # needed; some are used for convenience and visualization for this tutorial.
-library("terra")
+library("terra")
 library("samc")
 library("viridisLite")
 
@@ -234,7 +234,7 @@ 

Setup # Setup the details for our transition function -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -249,32 +249,36 @@

Basic Location Usage
 # A couple examples of using numeric locations
 mort_origin <- mortality(samc_obj, origin = 7)
-head(mort_origin) # The result is a vector. Let's see the first few elements
+head(mort_origin) # The result is a vector. Let's see the first few elements
 #> [1] 0.0004454945 0.0005970254 0.0006268049 0.0006652296 0.0007168680
-#> [6] 0.0007962162
-
+#> [6] 0.0007962162

+
+
 mort_dest <- mortality(samc_obj, dest = 13)
-head(mort_dest) # The result is a vector. Let's see the first few elements
+head(mort_dest) # The result is a vector. Let's see the first few elements
 #> [1] 0.0004952858 0.0005096278 0.0005283281 0.0005495412 0.0005727323
-#> [6] 0.0005978134
-
+#> [6] 0.0005978134
+
+
 mort_both <- mortality(samc_obj, origin = 7, dest = 13)
 mort_both # The result is a single value
-#> [1] 0.0006250264
-
+#> [1] 0.0006250264
+
+
 # The single value of mort_both simply is just extracted from one of the vector
 # results. So using both the origin and dest parameters is largely for convenience,
 # and helps to prevent accidental mistakes from trying to manually extract values
 # from the vectors
 mort_origin[13]
-#> [1] 0.0006250264
-mort_dest[7]
+#> [1] 0.0006250264
+
+mort_dest[7]
 #> [1] 0.0006250264

Viewing Location Values

-
+
 # Use the locate() function to get a raster that shows pixels or cells as
 # location values
 locations_map <- locate(samc_obj)
@@ -287,12 +291,12 @@ 

Viewing Location Values# top to bottom, it forms what appears to be a smooth gradient. If a user is # interested in identifying actual location values from this raster, they'll likely # have to save the raster and view it in external GIS software -plot(locations_map, col = viridis(1024)) +plot(locations_map, col = viridis(1024)) # There's a simple way to see visually where a particular location is. The location # will be shown as 1 (converted from TRUE), and all other locations will be shown # as 0 (converted from FALSE) -plot(locations_map == 277, col = viridis(2))

+plot(locations_map == 277, col = viridis(2))

@@ -306,24 +310,25 @@

Using Coordinates
+
 coords <- data.frame(x = c(50, 130),
                      y = c(23, 9))
 
 # Use the locate() function with coords to get location values
 locations <- locate(samc_obj, coords)
 
-plot(locations_map == locations[1], col = viridis(2))
-plot(locations_map == locations[2], col = viridis(2))
+plot(locations_map == locations[1], col = viridis(2))
+plot(locations_map == locations[2], col = viridis(2))
 
 # Use the locations in a function
 mort_1 <- mortality(samc_obj, origin = locations[1])
-head(mort_1)
+head(mort_1)
 #> [1] 0.0004313355 0.0005695849 0.0005833685 0.0005963590 0.0006070493
-#> [6] 0.0006144510
-
+#> [6] 0.0006144510
+
+
 mort_2 <- mortality(samc_obj, origin = locations[2])
-head(mort_2)
+head(mort_2)
 #> [1] 0.0001651789 0.0002113811 0.0002086714 0.0002057462 0.0002027257
 #> [6] 0.0001996758

@@ -340,7 +345,7 @@

Multiple locations
+
 # We're going to use a data.frame to manage our input and output vectors easily
 data <- data.frame(origin = c(45, 3, 99),
                    dest = c(102, 102, 33))
@@ -359,7 +364,7 @@ 

Multiple locationsCode Snippets vignette.

-
+
 # Get the result for all the pairwise combinations of two vectors of locations
 pairwise(mortality, samc_obj, 5:6, 23:25)
 #>   origin dest       result
@@ -389,7 +394,7 @@ 

Multiple locations

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-1.png b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-1.png index e9d9e1e..214ac37 100644 Binary files a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-1.png and b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-1.png differ diff --git a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-2.png b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-2.png index 17cb2fc..a976544 100644 Binary files a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-2.png and b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-3-2.png differ diff --git a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-1.png b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-1.png index 0a44d80..e36cbf2 100644 Binary files a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-1.png and b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-1.png differ diff --git a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-2.png b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-2.png index 1ccc583..e0ab530 100644 Binary files a/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-2.png and b/docs/articles/tutorial-locations_files/figure-html/unnamed-chunk-4-2.png differ diff --git a/docs/articles/tutorial-multiple-absorption.html b/docs/articles/tutorial-multiple-absorption.html index 2742656..b15f97f 100644 --- a/docs/articles/tutorial-multiple-absorption.html +++ b/docs/articles/tutorial-multiple-absorption.html @@ -6,7 +6,7 @@ Multiple Absorption Tutorial • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0
@@ -163,7 +163,7 @@

Multiple Absorption Tutorial

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/tutorial-multiple-absorption.Rmd @@ -196,7 +196,7 @@

Setup
 # First step is to load the libraries. Not all of these libraries are strictly
 # needed; some are used for convenience and visualization for this tutorial.
-library("terra")
+library("terra")
 library("samc")
 library("viridisLite")
 
@@ -221,11 +221,11 @@ 

Setup abs_data_b <- abs_data * p2 # With terra, make sure each layer has a unique name -names(abs_data_a) = "abs1" -names(abs_data_b) = "abs2" +names(abs_data_a) = "abs1" +names(abs_data_b) = "abs2" # Verify -all.equal(abs_data_a + abs_data_b, abs_data) +all.equal(abs_data_a + abs_data_b, abs_data) #> [1] "Names: 1 string mismatch" #> [2] "Attributes: < Component \"ptr\": Component \"names\": 1 string mismatch >"

@@ -240,7 +240,7 @@

Total (Single) Absorption
 # Setup the details for our transition function
-rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities
+rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities
            dir = 8, # Directions of the transitions. Either 4 or 8.
            sym = TRUE) # Is the function symmetric?
 
@@ -254,11 +254,12 @@ 

Total (Single) Absorption# When only working with total absorption, this version of mortality() returns # a named vector str(mort) -#> num [1:2624] 0.000783 0.000787 0.000704 0.000655 0.000621 ... - +#> num [1:2624] 0.000783 0.000787 0.000704 0.000655 0.000621 ...

+
+
 # Let's visualize it
 mort_map <- map(samc_obj, mort)
-plot(mort_map, xlab = "x", ylab = "y", col = viridis(256))
+plot(mort_map, xlab = "x", ylab = "y", col = viridis(256))

@@ -270,7 +271,7 @@

Multiple Absorption
+
 # Let's attach absorption layers to our samc object
 samc_obj$abs_states <- c(abs_data_a, abs_data_b)
 
@@ -283,31 +284,34 @@ 

Multiple Absorptionstr(mort_multiple) #> List of 3 #> $ total: num [1:2624] 0.000783 0.000787 0.000704 0.000655 0.000621 ... -#> $ abs1 : num [1:2624] 0.000164 0.000165 0.000147 0.000137 0.00013 ... -#> $ abs2 : num [1:2624] 0.000619 0.000622 0.000556 0.000518 0.000491 ... - +#> $ abs1 : num [1:2624] 1.90e-05 1.91e-05 1.71e-05 1.59e-05 1.51e-05 ... +#> $ abs2 : num [1:2624] 0.000764 0.000768 0.000687 0.000639 0.000606 ...

+
+
 # Let's visualize it
 multiple_map <- map(samc_obj, mort_multiple)
-multiple_map <- rast(multiple_map) # Convert the list to a multi-layer SpatRaster for plotting
-plot(multiple_map, xlab = "x", ylab = "y", col = viridis(256), nc = 1, nr = 3)
+multiple_map <- rast(multiple_map) # Convert the list to a multi-layer SpatRaster for plotting +plot(multiple_map, xlab = "x", ylab = "y", col = viridis(256), nc = 1, nr = 3)

-
+
 
 
 # Let's check some things.
 
 #First, the results of the decomposed layers in the list should add up to the total result
-all.equal(values(multiple_map[[1]], mat = FALSE),
-          values(multiple_map[[2]] + multiple_map[[3]], mat = FALSE))
-#> [1] TRUE
-# Alternatively, we could use the layer names:
-all.equal(values(multiple_map$total, mat = FALSE),
-          values(multiple_map$abs1 + multiple_map$abs2, mat = FALSE))
-#> [1] TRUE
-
+all.equal(values(multiple_map[[1]], mat = FALSE),
+          values(multiple_map[[2]] + multiple_map[[3]], mat = FALSE))
+#> [1] TRUE
+
+# Alternatively, we could use the layer names:
+all.equal(values(multiple_map$total, mat = FALSE),
+          values(multiple_map$abs1 + multiple_map$abs2, mat = FALSE))
+#> [1] TRUE
+
+
 # Second, notice in the plots above that the result for the single input and the total
 # result for the multiple input look very similar? That's because they are identical
-all.equal(mort, mort_multiple$total)
+all.equal(mort, mort_multiple$total)
 #> [1] TRUE
@@ -325,7 +329,7 @@

Partial Absorption Data -
+
+partial_map <- rast(partial_map) # Convert the list to a RasterStack for plotting
+plot(partial_map, xlab = "x", ylab = "y", col = viridis(256), nc = 1, nr = 3)

The second situation is where we might have multiple candidate models for a particular source of absorption. Rather than running the analysis once for every candidate, we can simply include them all and run the analysis once.

-
+
 # Create multiple versions of our first component. This might represent multiple
 # models or hypotheses we want to explore
 abs_1_models <- c(abs_data_a * 0.2,
@@ -349,7 +353,7 @@ 

Partial Absorption Data abs_data_a * 0.6, abs_data_a * 0.8, abs_data_a) -names(abs_1_models) <- c("abs1_2", "abs1_4", "abs1_6", "abs1_8", "abs1") +names(abs_1_models) <- c("abs1_2", "abs1_4", "abs1_6", "abs1_8", "abs1") samc_obj$abs_states <- abs_1_models mort_models <- mortality(samc_obj, origin = 1) @@ -357,8 +361,8 @@

Partial Absorption Data# Let's visualize it. Note that the results are not particularly interesting visually; # the only difference between these models is the scale models_map <- map(samc_obj, mort_models) -models_map <- rast(models_map) # Convert the list to a RasterStack for plotting -plot(models_map, xlab = "x", ylab = "y", col = viridis(256), nc = 2, nr = 3)

+models_map <- rast(models_map) # Convert the list to a RasterStack for plotting +plot(models_map, xlab = "x", ylab = "y", col = viridis(256), nc = 2, nr = 3)

@@ -401,7 +405,7 @@

Calculating Tot

Disabling Multiple Absorption

-
+
 # To remove all the absorption components
 samc_obj$abs_states <- NA
@@ -424,7 +428,7 @@

Disabling Multiple Absorption

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-2-1.png b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-2-1.png index 20fe347..c55822a 100644 Binary files a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-2-1.png and b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-2-1.png differ diff --git a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-3-1.png b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-3-1.png index 77cd6c8..23096ed 100644 Binary files a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-3-1.png and b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-3-1.png differ diff --git a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-4-1.png b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-4-1.png index 3b0ad06..1e36489 100644 Binary files a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-4-1.png and b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-4-1.png differ diff --git a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-5-1.png b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-5-1.png index 35704ae..4a29d19 100644 Binary files a/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-5-1.png and b/docs/articles/tutorial-multiple-absorption_files/figure-html/unnamed-chunk-5-1.png differ diff --git a/docs/articles/tutorial-temporal.html b/docs/articles/tutorial-temporal.html index a6bc311..9777b78 100644 --- a/docs/articles/tutorial-temporal.html +++ b/docs/articles/tutorial-temporal.html @@ -6,7 +6,7 @@ Temporal Analysis • samc - + @@ -33,7 +33,7 @@ samc - 3.2.1 + 3.3.0

@@ -163,7 +163,7 @@

Temporal Analysis

Andrew Marx

-

2023-05-12

+

2024-07-25

Source: vignettes/tutorial-temporal.Rmd @@ -185,7 +185,7 @@

Setup
 # First step is to load the libraries. Not all of these libraries are stricly
 # needed; some are used for convenience and visualization for this tutorial.
-library("terra")
+library("terra")
 library("samc")
 library("viridisLite")
 
@@ -201,7 +201,7 @@ 

Setup abs_data <- rasterize(abs_data) # Setup the details for our transition function -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -229,48 +229,26 @@

Temporal Analysis# The result is a list of vectors. Note that the list is named with the time steps str(results) -#> List of 4 -#> $ 10 : num [1:2624] 0.0246 0.0306 0.0261 0.0193 0.0125 ... -#> $ 100 : num [1:2624] 0.00256 0.00336 0.00338 0.00334 0.00326 ... -#> $ 1000 : num [1:2624] 0.000212 0.000284 0.000295 0.000307 0.00032 ... -#> $ 10000: num [1:2624] 3.09e-05 3.97e-05 3.93e-05 3.88e-05 3.83e-05 ... # We can take this list, and use map() to convert it to a list of RasterLayers. results_map <- map(samc_obj, results) str(results_map, max.level = 1) # max.level is to hide a lot of gory details -#> List of 4 -#> $ 10 :S4 class 'SpatRaster' [package "terra"] -#> $ 100 :S4 class 'SpatRaster' [package "terra"] -#> $ 1000 :S4 class 'SpatRaster' [package "terra"] -#> $ 10000:S4 class 'SpatRaster' [package "terra"] # A list of SpatRasters can be turned -results_stack <- rast(results_map) +results_stack <- rast(results_map) # Let's look at the names -names(results_stack) -#> [1] "10" "100" "1000" "10000" +names(results_stack) # RasterStacks are convenient for a lot of different things, like processing the # rasters all at once using spatial methods. But we're just going to plot them -plot(results_stack, xlab = "x", ylab = "y", col = viridis(256))

-

+plot(results_stack, xlab = "x", ylab = "y", col = viridis(256))

If you want more control, the following shows how to loop through the results using two different options

 # The results of individual time steps can be retrieved by either index or by name 
 results[[3]]
-#>  [1] 0.0002122761 0.0002838443 0.0002953125 0.0003074062 0.0003195378
-#>  [6] 0.0003313612 0.0003426443 0.0003532239 0.0003629837 0.0003718411
-#> [11] 0.0003797378 0.0003866344 0.0003925059 0.0003973388 0.0004011292
-#> [16] 0.0004038814 0.0004056069 0.0004063231 0.0004060532 0.0004048254
-#>  [ reached getOption("max.print") -- omitted 2604 entries ]
 results[["1000"]]
-#>  [1] 0.0002122761 0.0002838443 0.0002953125 0.0003074062 0.0003195378
-#>  [6] 0.0003313612 0.0003426443 0.0003532239 0.0003629837 0.0003718411
-#> [11] 0.0003797378 0.0003866344 0.0003925059 0.0003973388 0.0004011292
-#> [16] 0.0004038814 0.0004056069 0.0004063231 0.0004060532 0.0004048254
-#>  [ reached getOption("max.print") -- omitted 2604 entries ]
 
 # The latter is particularly useful in making reliable for loops because indexed
 # for loops can be harder to troubleshoot if something goes wrong. 
@@ -278,11 +256,9 @@ 

Temporal Analysisname <- as.character(ts) r <- results[[name]] r_map <- map(samc_obj, r) - plot(r_map, main = paste("Individual Location at Time", ts), xlab = "x", ylab = "y", col = viridis(256)) -}

-

-
-
+  plot(r_map, main = paste("Individual Location at Time", ts), xlab = "x", ylab = "y", col = viridis(256))
+}
+
 # For comparison, here is an indexed for loop that does the same thing
 for (i in 1:length(time_steps)) {
   name <- as.character(time_steps[i])
@@ -293,13 +269,12 @@ 

Temporal Analysis
+
 for (ts in time_steps) {
   dist <- distribution(samc_obj, origin = 1, time = ts)
   dist_map <- map(samc_obj, dist)
-  plot(dist_map, main = paste("Individual Location at Time", ts), xlab = "x", ylab = "y", col = viridis(256))
+  plot(dist_map, main = paste("Individual Location at Time", ts), xlab = "x", ylab = "y", col = viridis(256))
 }
-

@@ -320,7 +295,7 @@

Temporal Analysis

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/authors.html b/docs/authors.html index ebf10fc..2b1e505 100644 --- a/docs/authors.html +++ b/docs/authors.html @@ -1,5 +1,5 @@ -Authors and Citation • samcAuthors and Citation • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0

@@ -129,7 +129,7 @@
@@ -172,12 +172,12 @@

Citation

Marx A (????). samc: Spatial Absorbing Markov Chains. -R package version 3.2.1, https://andrewmarx.github.io/samc/. +R package version 3.3.0, https://andrewmarx.github.io/samc/.

@Manual{,
   title = {samc: Spatial Absorbing Markov Chains},
   author = {Andrew Marx},
-  note = {R package version 3.2.1},
+  note = {R package version 3.3.0},
   url = {https://andrewmarx.github.io/samc/},
 }

Marx AJ, Wang C, Sefair JA, Acevedo MA, Fletcher Jr. RJ (2020). @@ -207,7 +207,7 @@

Citation

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/index.html b/docs/index.html index 444a272..32d72b0 100644 --- a/docs/index.html +++ b/docs/index.html @@ -6,21 +6,13 @@ Spatial Absorbing Markov Chains • samc - + - + Changelog • samcChangelog • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -132,6 +132,25 @@

Changelog

Source: NEWS.md +
+ +
+

New features

+
  • New input options for metrics +
    • cond_passage(samc, init, dest)
    • +
    • dispersal(samc, origin, dest, time)
    • +
    • distribution(samc, init, dest, time)
    • +
    • mortality(samc, init, dest, time)
    • +
  • +
+
+

Other

+
  • Lot’s of internal refactoring and consolidation.
  • +
  • Various small memory and speed optimizations.
  • +
  • Various small fixes
  • +
  • License update
  • +
+
@@ -344,7 +363,7 @@
diff --git a/docs/pkgdown.yml b/docs/pkgdown.yml index 0d19519..13be190 100644 --- a/docs/pkgdown.yml +++ b/docs/pkgdown.yml @@ -1,5 +1,5 @@ -pandoc: 2.19.2 -pkgdown: 2.0.7 +pandoc: 3.1.11 +pkgdown: 2.0.9 pkgdown_sha: ~ articles: article-circuit-theory: article-circuit-theory.html @@ -21,5 +21,5 @@ articles: tutorial-locations: tutorial-locations.html tutorial-multiple-absorption: tutorial-multiple-absorption.html tutorial-temporal: tutorial-temporal.html -last_built: 2023-05-12T12:44Z +last_built: 2024-07-25T18:11Z diff --git a/docs/reference/absorption.html b/docs/reference/absorption.html index 941dafc..dc9b6e5 100644 --- a/docs/reference/absorption.html +++ b/docs/reference/absorption.html @@ -1,5 +1,5 @@ -Calculate absorption metrics — absorption • samcCalculate absorption metrics — absorption • samc samc - 3.2.1 + 3.3.0 @@ -253,7 +253,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 100% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -280,7 +280,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/char_null-class.html b/docs/reference/char_null-class.html index 1fba12f..25f239c 100644 --- a/docs/reference/char_null-class.html +++ b/docs/reference/char_null-class.html @@ -1,5 +1,5 @@ -samc char_null class — char_null-class • samcsamc char_null class — char_null-class • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -151,7 +151,7 @@

samc char_null class

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/check.html b/docs/reference/check.html index 38cc6cd..41004c5 100644 --- a/docs/reference/check.html +++ b/docs/reference/check.html @@ -1,5 +1,5 @@ -Check landscape data — check • samcCheck landscape data — check • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -249,7 +249,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 99% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -276,7 +276,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/cond_passage.html b/docs/reference/cond_passage.html index c951397..70e30ba 100644 --- a/docs/reference/cond_passage.html +++ b/docs/reference/cond_passage.html @@ -1,5 +1,5 @@ -Conditional Mean First Passage Time — cond_passage • samcConditional Mean First Passage Time — cond_passage • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -144,7 +144,10 @@

Conditional Mean First Passage Time

cond_passage(samc, dest) # S4 method for samc,missing,location,location -cond_passage(samc, origin, dest)
+cond_passage(samc, origin, dest) + +# S4 method for samc,ANY,missing,location +cond_passage(samc, init, dest)
@@ -154,7 +157,9 @@

Arguments

init
-

Placeholder/not currently implemented.

+

Sets the initial state \(\psi\) of the transients states. Input +must be able to pass the check function when compared against +the samc-class object. Can only contain positive finite values.

origin
@@ -260,7 +265,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 100% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -287,7 +292,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/dispersal.html b/docs/reference/dispersal.html index 8d10cf5..8b6661e 100644 --- a/docs/reference/dispersal.html +++ b/docs/reference/dispersal.html @@ -1,5 +1,5 @@ -Calculate dispersal metrics — dispersal • samcCalculate dispersal metrics — dispersal • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -140,6 +140,9 @@

Calculate dispersal metrics

dispersal(samc, init, origin, dest, time)
 
+# S4 method for samc,missing,location,location,numeric
+dispersal(samc, origin, dest, time)
+
 # S4 method for samc,missing,missing,location,numeric
 dispersal(samc, dest, time)
 
@@ -303,7 +306,7 @@ 

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 49% (~10s remaining) Computing: 99% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -330,7 +333,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/distribution.html b/docs/reference/distribution.html index 62a12c0..1b3f120 100644 --- a/docs/reference/distribution.html +++ b/docs/reference/distribution.html @@ -1,5 +1,5 @@ -Calculate distribution metrics — distribution • samcCalculate distribution metrics — distribution • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -153,7 +153,10 @@

Calculate distribution metrics

distribution(samc, origin, dest, time) # S4 method for samc,ANY,missing,missing,numeric -distribution(samc, init, time)
+distribution(samc, init, time) + +# S4 method for samc,ANY,missing,location,numeric +distribution(samc, init, dest, time)
@@ -288,7 +291,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -315,7 +318,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/example_maze.html b/docs/reference/example_maze.html index 9221ed7..ac2df4c 100644 --- a/docs/reference/example_maze.html +++ b/docs/reference/example_maze.html @@ -1,5 +1,5 @@ -Simple maze example — example_maze • samcSimple maze example — example_maze • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -162,7 +162,7 @@

Source

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/example_split_corridor.html b/docs/reference/example_split_corridor.html index c3b2e4e..b2fb328 100644 --- a/docs/reference/example_split_corridor.html +++ b/docs/reference/example_split_corridor.html @@ -1,5 +1,5 @@ -Simple split corridor example — example_split_corridor • samcSimple split corridor example — example_split_corridor • samcToy resistance data — example_toy_res • samcToy resistance data — example_toy_res • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -162,7 +162,7 @@

Source

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/index.html b/docs/reference/index.html index 1ddfd14..90b856b 100644 --- a/docs/reference/index.html +++ b/docs/reference/index.html @@ -1,5 +1,5 @@ -Function reference • samcFunction reference • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -160,7 +160,7 @@

Utility Functions

Map vector data

-

pairwise pairwise,function,samc,location,location-method pairwise,function,samc,location,missing-method

+

pairwise()

Pairwise analyses

@@ -236,7 +236,7 @@

Built-in Data
-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/locate.html b/docs/reference/locate.html index 8c28705..cccef80 100644 --- a/docs/reference/locate.html +++ b/docs/reference/locate.html @@ -1,5 +1,5 @@ -Get cell numbers — locate • samcGet cell numbers — locate • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -154,7 +154,7 @@

Arguments

xy
-

Any valid input to the y argument of the extract function in the raster package.

+

Any valid input to the y argument of the extract function in the raster package.

@@ -173,8 +173,8 @@

Details

associated with this data are excluded from the P matrix. This causes issues trying to determine the cell numbers that should be used in analyses.

The locate function operates more-or-less like the -cellFromXY function in the raster package, but unlike -cellFromXY, locate properly accounts for NA cells +cellFromXY function in the raster package, but unlike +cellFromXY, locate properly accounts for NA cells in identifying cell numbers from coordinate data.

This function can also be used if the samc object was created from matrix inputs for the resistance, absorption, and fidelity parameters. In this case, the @@ -182,15 +182,15 @@

Details

that (1,1) is the bottom left corner.

The xy parameter can also be excluded. In this case, the function returns a raster where the values of the cells contains the cell number.

-

Internally, this function relies on the extract function +

Internally, this function relies on the extract function from the raster package, and any valid input for the y argument of that function is valid here.

Examples

-
library(terra)
-#> terra 1.7.3
+    
library(terra)
+#> terra 1.7.78
 #> 
 #> Attaching package: ‘terra’
 #> The following object is masked from ‘package:samc’:
@@ -206,7 +206,7 @@ 

Examples

# Create samc-class object samc_obj <- samc(res_data, abs_data, - model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE)) + model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE)) # We can use locate() to return an object with the cell numbers encoded as data @@ -914,7 +914,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/location-class.html b/docs/reference/location-class.html index 144973f..db35d66 100644 --- a/docs/reference/location-class.html +++ b/docs/reference/location-class.html @@ -1,5 +1,5 @@ -location class — location-class • samclocation class — location-class • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0
@@ -158,7 +158,7 @@

Details

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/map.html b/docs/reference/map.html index d8943d4..c37c2fc 100644 --- a/docs/reference/map.html +++ b/docs/reference/map.html @@ -1,5 +1,5 @@ -Map vector data — map • samcMap vector data — map • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -198,7 +198,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -222,7 +222,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 99% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -249,7 +249,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/mat_null-class.html b/docs/reference/mat_null-class.html index 2474bfa..ee7e06e 100644 --- a/docs/reference/mat_null-class.html +++ b/docs/reference/mat_null-class.html @@ -1,5 +1,5 @@ -samc mat_null class — mat_null-class • samcsamc mat_null class — mat_null-class • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -151,7 +151,7 @@

samc mat_null class

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/mortality.html b/docs/reference/mortality.html index 08e94e5..2c1a46c 100644 --- a/docs/reference/mortality.html +++ b/docs/reference/mortality.html @@ -1,5 +1,5 @@ -Calculate mortality metrics — mortality • samcCalculate mortality metrics — mortality • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -155,6 +155,9 @@

Calculate mortality metrics

# S4 method for samc,ANY,missing,missing,numeric mortality(samc, init, time) +# S4 method for samc,ANY,missing,location,numeric +mortality(samc, init, dest, time) + # S4 method for samc,missing,missing,missing,missing mortality(samc) @@ -168,7 +171,10 @@

Calculate mortality metrics

mortality(samc, origin, dest) # S4 method for samc,ANY,missing,missing,missing -mortality(samc, init)
+mortality(samc, init) + +# S4 method for samc,ANY,missing,location,missing +mortality(samc, init, dest)
@@ -307,7 +313,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -331,7 +337,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 99% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -358,7 +364,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/pairwise.html b/docs/reference/pairwise.html index 172ba6c..22b7df3 100644 --- a/docs/reference/pairwise.html +++ b/docs/reference/pairwise.html @@ -1,5 +1,5 @@ -Pairwise analyses — pairwise • samcPairwise analyses — pairwise • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -140,10 +140,10 @@

Pairwise analyses

pairwise(fun, samc, origin, dest)
 
-# S4 method for `function`,samc,location,location
+# S4 method for function,samc,location,location
 pairwise(fun, samc, origin, dest)
 
-# S4 method for `function`,samc,location,missing
+# S4 method for function,samc,location,missing
 pairwise(fun, samc, origin)
@@ -204,7 +204,7 @@

Examples

# Create samc-class object samc_obj <- samc(res_data, abs_data, - model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE)) + model = list(fun = function(x) 1/mean(x), dir = 8, sym = TRUE)) # pairwise() example pw <- pairwise(cond_passage, samc_obj, origin = 1:4, dest = 5) @@ -239,7 +239,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/rasterize.html b/docs/reference/rasterize.html index 99c5de9..e276e2d 100644 --- a/docs/reference/rasterize.html +++ b/docs/reference/rasterize.html @@ -1,5 +1,5 @@ -Rasterize input — rasterize • samcRasterize input — rasterize • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -201,7 +201,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -225,7 +225,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 100% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -252,7 +252,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/samc-class-access.html b/docs/reference/samc-class-access.html index d461bbb..b7ca307 100644 --- a/docs/reference/samc-class-access.html +++ b/docs/reference/samc-class-access.html @@ -1,5 +1,5 @@ -Access samc-class components — samc-class-access • samcAccess samc-class components — samc-class-access • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -171,7 +171,7 @@

Value

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/samc-class-modify.html b/docs/reference/samc-class-modify.html index 2197860..0aa3ea7 100644 --- a/docs/reference/samc-class-modify.html +++ b/docs/reference/samc-class-modify.html @@ -1,5 +1,5 @@ -Modify samc-class components — samc-class-modify • samcModify samc-class components — samc-class-modify • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -175,7 +175,7 @@

Value

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/samc-class.html b/docs/reference/samc-class.html index 9bd13c3..8224953 100644 --- a/docs/reference/samc-class.html +++ b/docs/reference/samc-class.html @@ -1,5 +1,5 @@ -samc class — samc-class • samcsamc class — samc-class • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -212,6 +212,10 @@

Slots

Information about the data source for the P matrix

+
nodes
+

The number of nodes in the graph

+ +
map

Used to verify landscape inputs and mapping of vector data

@@ -220,6 +224,10 @@

Slots

Matrix used to map location and direction to edges description

+
prob_mat
+

Matric for CRW probabilities

+ +
names

Names of the transient states

@@ -258,7 +266,7 @@

Slots

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/samc.html b/docs/reference/samc.html index 1da5618..588a06e 100644 --- a/docs/reference/samc.html +++ b/docs/reference/samc.html @@ -1,5 +1,5 @@ -Create an samc object — samc • samcCreate an samc object — samc • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -168,15 +168,15 @@

Create an samc object

Arguments

data
-

A SpatRaster-class or RasterLayer-class or matrix or Matrix package dgCMatrix sparse matrix.

+

A SpatRaster-class or RasterLayer-class or matrix or Matrix package dgCMatrix sparse matrix.

absorption
-

A SpatRaster-class or RasterLayer-class or matrix

+

A SpatRaster-class or RasterLayer-class or matrix

fidelity
-

A SpatRaster-class or RasterLayer-class or matrix

+

A SpatRaster-class or RasterLayer-class or matrix

model
@@ -284,7 +284,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -308,7 +308,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 100% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -335,7 +335,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/samc_data-class.html b/docs/reference/samc_data-class.html index 43dcd6b..d95cd14 100644 --- a/docs/reference/samc_data-class.html +++ b/docs/reference/samc_data-class.html @@ -1,5 +1,5 @@ -data class — samc_data-class • samcdata class — samc_data-class • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -168,7 +168,7 @@

Slots

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/survival.html b/docs/reference/survival.html index 491568b..50d1fd2 100644 --- a/docs/reference/survival.html +++ b/docs/reference/survival.html @@ -1,5 +1,5 @@ -Calculate survival metrics — survival • samcCalculate survival metrics — survival • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -138,12 +138,15 @@

Calculate survival metrics

-
survival(samc, init)
+    
survival(samc, init, origin)
 
-# S4 method for samc,missing
+# S4 method for samc,missing,missing
 survival(samc)
 
-# S4 method for samc,ANY
+# S4 method for samc,missing,location
+survival(samc, origin)
+
+# S4 method for samc,ANY,missing
 survival(samc, init)
@@ -158,6 +161,13 @@

Arguments

must be able to pass the check function when compared against the samc-class object. Can only contain positive finite values.

+ +
origin
+

A positive integer or character name representing transient state +\(\mathit{i}\). Corresponds to row \(\mathit{i}\) of matrix \(\mathbf{P}\) +in the samc-class object. When paired with the dest +parameter, multiple values may be provided as a vector.

+

Value

@@ -204,7 +214,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -228,7 +238,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 49% (~10s remaining) Computing: 99% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -255,7 +265,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/visitation.html b/docs/reference/visitation.html index 52ceed1..6e1efc8 100644 --- a/docs/reference/visitation.html +++ b/docs/reference/visitation.html @@ -1,5 +1,5 @@ -Calculate visitation metrics — visitation • samcCalculate visitation metrics — visitation • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -312,7 +312,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -336,7 +336,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~10s remaining) Computing: 99% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -363,7 +363,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/reference/visitation_net.html b/docs/reference/visitation_net.html index 8512832..6dbbdd6 100644 --- a/docs/reference/visitation_net.html +++ b/docs/reference/visitation_net.html @@ -1,5 +1,5 @@ -Calculate net visitation — visitation_net • samcCalculate net visitation — visitation_net • samc @@ -17,7 +17,7 @@ samc - 3.2.1 + 3.3.0 @@ -207,7 +207,7 @@

Examples

#> [1] TRUE # Setup the details for a random-walk model -rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities +rw_model <- list(fun = function(x) 1/mean(x), # Function for calculating transition probabilities dir = 8, # Directions of the transitions. Either 4 or 8. sym = TRUE) # Is the function symmetric? @@ -231,7 +231,7 @@

Examples

#> Cached diagonal not found. #> Performing setup. This can take several minutes... Complete. #> Calculating matrix inverse diagonal... -#> Computing: 50% (~9s remaining) Computing: 100% (~0s remaining) Computing: 100% (done) +#> Computing: 100% (done) #> Complete #> Diagonal has been cached. Continuing with metric calculation... visit <- visitation(samc_obj, dest = 4) @@ -258,7 +258,7 @@

Examples

-

Site built with pkgdown 2.0.7.

+

Site built with pkgdown 2.0.9.

diff --git a/docs/sitemap.xml b/docs/sitemap.xml index 6a3fa23..166bbf7 100644 --- a/docs/sitemap.xml +++ b/docs/sitemap.xml @@ -6,6 +6,9 @@ /LICENSE-text.html + + /LICENSE.html + /articles/article-circuit-theory.html diff --git a/index.md b/index.md index 98663f0..8db25b4 100644 --- a/index.md +++ b/index.md @@ -29,10 +29,15 @@ Marx, A.J., Wang, C., Sefair, J.A., Acevedo, M.A. and Fletcher, R.J., Jr. (2020) ### **Publications** -This is a list of publications where the samc package was applied to a research question: +This is a list of publications where the samc package was used in some way: +- [**Predicting dispersal and conflict risk for wolf recolonization in Colorado**](http://dx.doi.org/10.1111/1365-2664.14504) *Journal of Applied Ecology (Sep 2023)* +- [**A framework for linking dispersal biology to connectivity across landscapes**](http://dx.doi.org/10.1007/s10980-023-01741-8) *Landscape Ecology (Jul 2023)* +- [**Comparison and parallel implementation of alternative moving-window metrics of the connectivity of protected areas across large landscapes**](http://dx.doi.org/10.1007/s10980-023-01619-9) *Landscape Ecology (Mar 2023)* +- [**Mapping the connectivity–conflict interface to inform conservation**](http://dx.doi.org/10.1073/pnas.2211482119) *PNAS (Dec 2022)* - [**Landscape connectivity for an endangered carnivore: habitat conservation and road mitigation for ocelots in the US**](http://dx.doi.org/10.1007/s10980-022-01569-8) *Landscape Ecology (Dec 2022)* -- [**Extending isolation by resistance to predict genetic connectivity**](https://doi.org/10.1111/2041-210X.13975) *Methods in Ecology and Evolution (Sep 2022)* +- [**Extending isolation by resistance to predict genetic connectivity**](http://doi.org/10.1111/2041-210X.13975) *Methods in Ecology and Evolution (Sep 2022)* +- [**Defining and quantifying effective connectivity of landscapes for species' movements**](http://dx.doi.org/10.1111/ecog.05351) *Ecography (Mar 2021)* ### **Version 3** @@ -66,6 +71,12 @@ If you have an error, make sure you are using the newest version of the package. We have a Github discussions page for anything and everything related to the package here: [Github Discussions](https://github.com/andrewmarx/samc/discussions) +### **License** + +By default, package code is licensed under AGPLv3. Some code files derived from 3rd party sources may be licensed under GPLv3 and will have a comment to indicate this is the case. + +Website materials are licensed under CC BY-NC-SA 4.0. + ### References Fletcher, R.J., Jr., Sefair, J.A., Wang, C., Poli, C.L., Smith, T.A.H., Bruna, E.M., Holt, R.D., Barfield, M., Marx, A.J. and Acevedo, M.A. (2019), Towards a unified framework for connectivity that disentangles movement and mortality in space and time. Ecol Lett, 22: 1680-1689. https://doi.org/10.1111/ele.13333 diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index cea6f47..553de5f 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -14,7 +14,7 @@ Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); #endif // cond_t -Rcpp::NumericVector cond_t(Eigen::Map >& IQ, Eigen::VectorXd& qj); +Rcpp::List cond_t(Eigen::Map >& IQ, Eigen::VectorXd& qj); RcppExport SEXP _samc_cond_t(SEXP IQSEXP, SEXP qjSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; @@ -26,7 +26,7 @@ BEGIN_RCPP END_RCPP } // cond_t_iter -Rcpp::NumericVector cond_t_iter(Eigen::Map >& IQ, Eigen::VectorXd& qj); +Rcpp::List cond_t_iter(Eigen::Map >& IQ, Eigen::VectorXd& qj); RcppExport SEXP _samc_cond_t_iter(SEXP IQSEXP, SEXP qjSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; @@ -143,69 +143,29 @@ BEGIN_RCPP return rcpp_result_gen; END_RCPP } -// psid_long -Rcpp::NumericVector psid_long(Eigen::Map >& M, const Eigen::VectorXd& psi, const Eigen::VectorXd& dg, Rcpp::XPtr& SC); -RcppExport SEXP _samc_psid_long(SEXP MSEXP, SEXP psiSEXP, SEXP dgSEXP, SEXP SCSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type psi(psiSEXP); - Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type dg(dgSEXP); - Rcpp::traits::input_parameter< Rcpp::XPtr& >::type SC(SCSEXP); - rcpp_result_gen = Rcpp::wrap(psid_long(M, psi, dg, SC)); - return rcpp_result_gen; -END_RCPP -} -// psid_long_iter -Rcpp::NumericVector psid_long_iter(Eigen::Map >& M, const Eigen::VectorXd& psi, const Eigen::VectorXd& dg); -RcppExport SEXP _samc_psid_long_iter(SEXP MSEXP, SEXP psiSEXP, SEXP dgSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type psi(psiSEXP); - Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type dg(dgSEXP); - rcpp_result_gen = Rcpp::wrap(psid_long_iter(M, psi, dg)); - return rcpp_result_gen; -END_RCPP -} // qpow_row -Rcpp::List qpow_row(Eigen::Map >& M, const int row, Rcpp::NumericVector steps); -RcppExport SEXP _samc_qpow_row(SEXP MSEXP, SEXP rowSEXP, SEXP stepsSEXP) { +Rcpp::List qpow_row(Eigen::Map >& M, const Eigen::Map& vec, Rcpp::NumericVector steps); +RcppExport SEXP _samc_qpow_row(SEXP MSEXP, SEXP vecSEXP, SEXP stepsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type row(rowSEXP); + Rcpp::traits::input_parameter< const Eigen::Map& >::type vec(vecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type steps(stepsSEXP); - rcpp_result_gen = Rcpp::wrap(qpow_row(M, row, steps)); + rcpp_result_gen = Rcpp::wrap(qpow_row(M, vec, steps)); return rcpp_result_gen; END_RCPP } // qpow_col -Rcpp::List qpow_col(Eigen::Map >& M, const int col, Rcpp::NumericVector steps); -RcppExport SEXP _samc_qpow_col(SEXP MSEXP, SEXP colSEXP, SEXP stepsSEXP) { +Rcpp::List qpow_col(Eigen::Map >& M, const Eigen::Map& vec, Rcpp::NumericVector steps); +RcppExport SEXP _samc_qpow_col(SEXP MSEXP, SEXP vecSEXP, SEXP stepsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type col(colSEXP); - Rcpp::traits::input_parameter< Rcpp::NumericVector >::type steps(stepsSEXP); - rcpp_result_gen = Rcpp::wrap(qpow_col(M, col, steps)); - return rcpp_result_gen; -END_RCPP -} -// psiq -Rcpp::List psiq(Eigen::Map >& M, const Eigen::Map& psi, Rcpp::NumericVector steps); -RcppExport SEXP _samc_psiq(SEXP MSEXP, SEXP psiSEXP, SEXP stepsSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const Eigen::Map& >::type psi(psiSEXP); + Rcpp::traits::input_parameter< const Eigen::Map& >::type vec(vecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type steps(stepsSEXP); - rcpp_result_gen = Rcpp::wrap(psiq(M, psi, steps)); + rcpp_result_gen = Rcpp::wrap(qpow_col(M, vec, steps)); return rcpp_result_gen; END_RCPP } @@ -256,116 +216,78 @@ BEGIN_RCPP END_RCPP } // sum_qpow_row -Rcpp::List sum_qpow_row(Eigen::Map >& M, const int row, Rcpp::NumericVector steps); -RcppExport SEXP _samc_sum_qpow_row(SEXP MSEXP, SEXP rowSEXP, SEXP stepsSEXP) { +Rcpp::List sum_qpow_row(Eigen::Map >& M, const Eigen::Map& vec, Rcpp::NumericVector steps); +RcppExport SEXP _samc_sum_qpow_row(SEXP MSEXP, SEXP vecSEXP, SEXP stepsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type row(rowSEXP); + Rcpp::traits::input_parameter< const Eigen::Map& >::type vec(vecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type steps(stepsSEXP); - rcpp_result_gen = Rcpp::wrap(sum_qpow_row(M, row, steps)); + rcpp_result_gen = Rcpp::wrap(sum_qpow_row(M, vec, steps)); return rcpp_result_gen; END_RCPP } // sum_qpow_col -Rcpp::List sum_qpow_col(Eigen::Map >& M, const int& col, Rcpp::NumericVector steps); -RcppExport SEXP _samc_sum_qpow_col(SEXP MSEXP, SEXP colSEXP, SEXP stepsSEXP) { +Rcpp::List sum_qpow_col(Eigen::Map >& M, const Eigen::Map& vec, Rcpp::NumericVector steps); +RcppExport SEXP _samc_sum_qpow_col(SEXP MSEXP, SEXP vecSEXP, SEXP stepsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int& >::type col(colSEXP); + Rcpp::traits::input_parameter< const Eigen::Map& >::type vec(vecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type steps(stepsSEXP); - rcpp_result_gen = Rcpp::wrap(sum_qpow_col(M, col, steps)); - return rcpp_result_gen; -END_RCPP -} -// sum_psiqpow -Rcpp::List sum_psiqpow(Eigen::Map >& M, const Eigen::Map& psi, Rcpp::NumericVector steps); -RcppExport SEXP _samc_sum_psiqpow(SEXP MSEXP, SEXP psiSEXP, SEXP stepsSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const Eigen::Map& >::type psi(psiSEXP); - Rcpp::traits::input_parameter< Rcpp::NumericVector >::type steps(stepsSEXP); - rcpp_result_gen = Rcpp::wrap(sum_psiqpow(M, psi, steps)); + rcpp_result_gen = Rcpp::wrap(sum_qpow_col(M, vec, steps)); return rcpp_result_gen; END_RCPP } // f_row -Rcpp::NumericVector f_row(const Eigen::SparseMatrix& M, const int row, Rcpp::XPtr& SC); -RcppExport SEXP _samc_f_row(SEXP MSEXP, SEXP rowSEXP, SEXP SCSEXP) { +Rcpp::NumericVector f_row(const Eigen::SparseMatrix& M, const Eigen::VectorXd& vec, Rcpp::XPtr& SC); +RcppExport SEXP _samc_f_row(SEXP MSEXP, SEXP vecSEXP, SEXP SCSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< const Eigen::SparseMatrix& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type row(rowSEXP); + Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type vec(vecSEXP); Rcpp::traits::input_parameter< Rcpp::XPtr& >::type SC(SCSEXP); - rcpp_result_gen = Rcpp::wrap(f_row(M, row, SC)); + rcpp_result_gen = Rcpp::wrap(f_row(M, vec, SC)); return rcpp_result_gen; END_RCPP } // f_row_iter -Rcpp::NumericVector f_row_iter(Eigen::SparseMatrix& M, const int row); -RcppExport SEXP _samc_f_row_iter(SEXP MSEXP, SEXP rowSEXP) { +Rcpp::NumericVector f_row_iter(Eigen::SparseMatrix& M, const Eigen::VectorXd& vec); +RcppExport SEXP _samc_f_row_iter(SEXP MSEXP, SEXP vecSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::SparseMatrix& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type row(rowSEXP); - rcpp_result_gen = Rcpp::wrap(f_row_iter(M, row)); + Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type vec(vecSEXP); + rcpp_result_gen = Rcpp::wrap(f_row_iter(M, vec)); return rcpp_result_gen; END_RCPP } // f_col -Rcpp::NumericVector f_col(Eigen::Map >& M, const int col, Rcpp::XPtr& SC); -RcppExport SEXP _samc_f_col(SEXP MSEXP, SEXP colSEXP, SEXP SCSEXP) { +Rcpp::NumericVector f_col(Eigen::Map >& M, const Eigen::VectorXd& vec, Rcpp::XPtr& SC); +RcppExport SEXP _samc_f_col(SEXP MSEXP, SEXP vecSEXP, SEXP SCSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type col(colSEXP); + Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type vec(vecSEXP); Rcpp::traits::input_parameter< Rcpp::XPtr& >::type SC(SCSEXP); - rcpp_result_gen = Rcpp::wrap(f_col(M, col, SC)); + rcpp_result_gen = Rcpp::wrap(f_col(M, vec, SC)); return rcpp_result_gen; END_RCPP } // f_col_iter -Rcpp::NumericVector f_col_iter(Eigen::Map >& M, const int col); -RcppExport SEXP _samc_f_col_iter(SEXP MSEXP, SEXP colSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< const int >::type col(colSEXP); - rcpp_result_gen = Rcpp::wrap(f_col_iter(M, col)); - return rcpp_result_gen; -END_RCPP -} -// psif -Rcpp::NumericVector psif(Eigen::Map >& M, Eigen::VectorXd& psi, Rcpp::XPtr& SC); -RcppExport SEXP _samc_psif(SEXP MSEXP, SEXP psiSEXP, SEXP SCSEXP) { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< Eigen::VectorXd& >::type psi(psiSEXP); - Rcpp::traits::input_parameter< Rcpp::XPtr& >::type SC(SCSEXP); - rcpp_result_gen = Rcpp::wrap(psif(M, psi, SC)); - return rcpp_result_gen; -END_RCPP -} -// psif_iter -Rcpp::NumericVector psif_iter(Eigen::Map >& M, Eigen::VectorXd& psi); -RcppExport SEXP _samc_psif_iter(SEXP MSEXP, SEXP psiSEXP) { +Rcpp::NumericVector f_col_iter(Eigen::Map >& M, const Eigen::VectorXd& vec); +RcppExport SEXP _samc_f_col_iter(SEXP MSEXP, SEXP vecSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Eigen::Map >& >::type M(MSEXP); - Rcpp::traits::input_parameter< Eigen::VectorXd& >::type psi(psiSEXP); - rcpp_result_gen = Rcpp::wrap(psif_iter(M, psi)); + Rcpp::traits::input_parameter< const Eigen::VectorXd& >::type vec(vecSEXP); + rcpp_result_gen = Rcpp::wrap(f_col_iter(M, vec)); return rcpp_result_gen; END_RCPP } @@ -381,24 +303,18 @@ static const R_CallMethodDef CallEntries[] = { {"_samc_sum_qn_q_iter", (DL_FUNC) &_samc_sum_qn_q_iter, 4}, {"_samc_diagf_par", (DL_FUNC) &_samc_diagf_par, 2}, {"_samc_diagf_par_iter", (DL_FUNC) &_samc_diagf_par_iter, 2}, - {"_samc_psid_long", (DL_FUNC) &_samc_psid_long, 4}, - {"_samc_psid_long_iter", (DL_FUNC) &_samc_psid_long_iter, 3}, {"_samc_qpow_row", (DL_FUNC) &_samc_qpow_row, 3}, {"_samc_qpow_col", (DL_FUNC) &_samc_qpow_col, 3}, - {"_samc_psiq", (DL_FUNC) &_samc_psiq, 3}, {"_samc_sum_qpowrv", (DL_FUNC) &_samc_sum_qpowrv, 3}, {"_samc_solver_cache", (DL_FUNC) &_samc_solver_cache, 0}, {"_samc_f1", (DL_FUNC) &_samc_f1, 2}, {"_samc_f1_iter", (DL_FUNC) &_samc_f1_iter, 1}, {"_samc_sum_qpow_row", (DL_FUNC) &_samc_sum_qpow_row, 3}, {"_samc_sum_qpow_col", (DL_FUNC) &_samc_sum_qpow_col, 3}, - {"_samc_sum_psiqpow", (DL_FUNC) &_samc_sum_psiqpow, 3}, {"_samc_f_row", (DL_FUNC) &_samc_f_row, 3}, {"_samc_f_row_iter", (DL_FUNC) &_samc_f_row_iter, 2}, {"_samc_f_col", (DL_FUNC) &_samc_f_col, 3}, {"_samc_f_col_iter", (DL_FUNC) &_samc_f_col_iter, 2}, - {"_samc_psif", (DL_FUNC) &_samc_psif, 3}, - {"_samc_psif_iter", (DL_FUNC) &_samc_psif_iter, 2}, {NULL, NULL, 0} }; diff --git a/src/cond_passage.cpp b/src/cond_passage.cpp index f814655..c7a149b 100644 --- a/src/cond_passage.cpp +++ b/src/cond_passage.cpp @@ -1,38 +1,36 @@ -// Copyright (c) 2020 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include // [[Rcpp::export(".cond_t")]] -Rcpp::NumericVector cond_t(Eigen::Map > &IQ, Eigen::VectorXd &qj) +Rcpp::List cond_t(Eigen::Map > &IQ, Eigen::VectorXd &qj) { Eigen::SparseLU > solver; solver.compute(IQ); Eigen::VectorXd b = solver.solve(qj); + Eigen::VectorXd fb = solver.solve(b); - solver.compute(IQ * b.asDiagonal()); + Rcpp::List res = Rcpp::List::create(Rcpp::Named("b") = b, Rcpp::Named("fb") = fb); - Eigen::VectorXd res = solver.solve(b); - - return Rcpp::wrap(res); + return res; } // [[Rcpp::export(".cond_t_iter")]] -Rcpp::NumericVector cond_t_iter(Eigen::Map > &IQ, Eigen::VectorXd &qj) +Rcpp::List cond_t_iter(Eigen::Map > &IQ, Eigen::VectorXd &qj) { Eigen::BiCGSTAB, Eigen::IncompleteLUT > solver; solver.compute(IQ); Eigen::VectorXd b = solver.solve(qj); + Eigen::VectorXd fb = solver.solve(b); - solver.compute(IQ * b.asDiagonal()); - - Eigen::VectorXd res = solver.solve(b); + Rcpp::List res = Rcpp::List::create(Rcpp::Named("b") = b, Rcpp::Named("fb") = fb); - return Rcpp::wrap(res); + return res; } diff --git a/src/dispersal.cpp b/src/dispersal.cpp index ffc07bd..33b3e3f 100644 --- a/src/dispersal.cpp +++ b/src/dispersal.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2019 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include @@ -170,28 +170,3 @@ Rcpp::NumericVector diagf_par_iter(Eigen::Map > &M, return Rcpp::wrap(dg); } - - -// [[Rcpp::export(".psid_long")]] -Rcpp::NumericVector psid_long(Eigen::Map > &M, - const Eigen::VectorXd &psi, const Eigen::VectorXd &dg, - Rcpp::XPtr &SC) -{ - SC->buildSolver(M.transpose(), "mt"); - - Eigen::VectorXd psiF = SC->solver().solve(psi) - psi; - - return Rcpp::wrap(psiF.cwiseQuotient(dg)); -} - -// [[Rcpp::export(".psid_long_iter")]] -Rcpp::NumericVector psid_long_iter(Eigen::Map > &M, const Eigen::VectorXd &psi, const Eigen::VectorXd &dg) -{ - Eigen::BiCGSTAB, Eigen::IncompleteLUT > solver; - - solver.compute(M.transpose()); - - Eigen::VectorXd psiF = solver.solve(psi) - psi; - - return Rcpp::wrap(psiF.cwiseQuotient(dg)); -} diff --git a/src/distribution.cpp b/src/distribution.cpp index 77fe17a..bfa35a7 100644 --- a/src/distribution.cpp +++ b/src/distribution.cpp @@ -1,20 +1,19 @@ -// Copyright (c) 2019 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include // [[Rcpp::export(".qpow_row")]] -Rcpp::List qpow_row(Eigen::Map > &M, const int row, Rcpp::NumericVector steps) +Rcpp::List qpow_row(Eigen::Map > &M, const Eigen::Map &vec, Rcpp::NumericVector steps) { int n = steps.size(); Rcpp::List res = Rcpp::List::create(); - Eigen::RowVectorXd time_res = M.row(row-1); + Eigen::RowVectorXd time_res = vec; for(int i = 1; i < n; i++) { - for (int j = steps[i - 1]; j < steps[i]; j++) { if(i % 1000 == 0) Rcpp::checkUserInterrupt(); time_res = time_res * M; @@ -27,13 +26,13 @@ Rcpp::List qpow_row(Eigen::Map > &M, const int row, } // [[Rcpp::export(".qpow_col")]] -Rcpp::List qpow_col(Eigen::Map > &M, const int col, Rcpp::NumericVector steps) +Rcpp::List qpow_col(Eigen::Map > &M, const Eigen::Map &vec, Rcpp::NumericVector steps) { int n = steps.size(); Rcpp::List res = Rcpp::List::create(); - Eigen::VectorXd time_res = M.col(col-1); + Eigen::VectorXd time_res = M * vec; for(int i = 1; i < n; i++) { for (int j = steps[i - 1]; j < steps[i]; j++) { @@ -46,24 +45,3 @@ Rcpp::List qpow_col(Eigen::Map > &M, const int col, return res; } - -// [[Rcpp::export(".psiq")]] -Rcpp::List psiq(Eigen::Map > &M, const Eigen::Map &psi, Rcpp::NumericVector steps) -{ - int n = steps.size(); - - Rcpp::List res = Rcpp::List::create(); - - Eigen::RowVectorXd time_res = psi; - - for(int i = 1; i < n; i++) { - for (int j = steps[i - 1]; j < steps[i]; j++) { - if(i % 1000 == 0) Rcpp::checkUserInterrupt(); - time_res = time_res * M; - } - - res.push_back(time_res, std::to_string((int)steps[i])); - } - - return res; -} diff --git a/src/mortality.cpp b/src/mortality.cpp index 535d2ee..508b809 100644 --- a/src/mortality.cpp +++ b/src/mortality.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2019-2023 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include diff --git a/src/samc_types.h b/src/samc_types.h index 5e4ff39..a198c42 100644 --- a/src/samc_types.h +++ b/src/samc_types.h @@ -1,3 +1,6 @@ +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. + #ifndef SAMC_TYPES_H #define SAMC_TYPES_H diff --git a/src/solver-cache.cpp b/src/solver-cache.cpp index 77945ff..3967f0f 100644 --- a/src/solver-cache.cpp +++ b/src/solver-cache.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2022 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include diff --git a/src/solver-cache.h b/src/solver-cache.h index 235ce08..a3201d8 100644 --- a/src/solver-cache.h +++ b/src/solver-cache.h @@ -1,5 +1,5 @@ -// Copyright (c) 2022 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #ifndef SOLVERCACHE_H #define SOLVERCACHE_H diff --git a/src/survival.cpp b/src/survival.cpp index 3b1307e..e988409 100644 --- a/src/survival.cpp +++ b/src/survival.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2019 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include diff --git a/src/visitation.cpp b/src/visitation.cpp index a302714..aaaff3e 100644 --- a/src/visitation.cpp +++ b/src/visitation.cpp @@ -1,5 +1,5 @@ -// Copyright (c) 2019-2023 Andrew Marx. All rights reserved. -// Licensed under GPLv3.0. See LICENSE file in the project root for details. +// Copyright (c) 2024 Andrew Marx where applicable. +// Licensed under AGPLv3.0. See LICENSE file in the project root for details. #include #include @@ -9,22 +9,20 @@ #include "solver-cache.h" // [[Rcpp::export(".sum_qpow_row")]] -Rcpp::List sum_qpow_row(Eigen::Map > &M, const int row, Rcpp::NumericVector steps) +Rcpp::List sum_qpow_row(Eigen::Map > &M, const Eigen::Map &vec, Rcpp::NumericVector steps) { int n = steps.size(); Rcpp::List res = Rcpp::List::create(); - Eigen::RowVectorXd row_vec = Eigen::RowVectorXd::Zero(M.rows()); - row_vec(row - 1) = 1; - - Eigen::RowVectorXd time_res = row_vec; + Eigen::RowVectorXd vecq = vec; + Eigen::RowVectorXd time_res = vec; for(int i = 1; i < n; i++) { for (int j = steps[i - 1]; j < steps[i]; j++) { if(i % 1000 == 0) Rcpp::checkUserInterrupt(); - row_vec = row_vec * M; - time_res = time_res + row_vec; + vecq = vecq * M; + time_res = time_res + vecq; } res.push_back(time_res, std::to_string((int)steps[i])); @@ -34,17 +32,14 @@ Rcpp::List sum_qpow_row(Eigen::Map > &M, const int r } // [[Rcpp::export(".sum_qpow_col")]] -Rcpp::List sum_qpow_col(Eigen::Map > &M, const int &col, Rcpp::NumericVector steps) +Rcpp::List sum_qpow_col(Eigen::Map > &M, const Eigen::Map &vec, Rcpp::NumericVector steps) { int n = steps.size(); Rcpp::List res = Rcpp::List::create(); - Eigen::VectorXd col_vec = Eigen::VectorXd::Zero(M.rows()); - col_vec(col-1) = 1; - - Eigen::VectorXd qc = col_vec; - Eigen::VectorXd time_res = col_vec; + Eigen::VectorXd qc = vec; + Eigen::VectorXd time_res = vec; for(int i = 1; i < n; i++) { for (int j = steps[i - 1]; j < steps[i]; j++) { @@ -59,62 +54,31 @@ Rcpp::List sum_qpow_col(Eigen::Map > &M, const int & return res; } -// [[Rcpp::export(".sum_psiqpow")]] -Rcpp::List sum_psiqpow(Eigen::Map > &M, const Eigen::Map &psi, Rcpp::NumericVector steps) -{ - int n = steps.size(); - - Rcpp::List res = Rcpp::List::create(); - - Eigen::RowVectorXd psiq = psi; - Eigen::RowVectorXd time_res = psi; - - for(int i = 1; i < n; i++) { - for (int j = steps[i - 1]; j < steps[i]; j++) { - if(i % 1000 == 0) Rcpp::checkUserInterrupt(); - psiq = psiq * M; - time_res = time_res + psiq; - } - - res.push_back(time_res, std::to_string((int)steps[i])); - } - - return res; -} // [[Rcpp::export(".f_row")]] -Rcpp::NumericVector f_row(const Eigen::SparseMatrix &M, const int row, Rcpp::XPtr &SC) +Rcpp::NumericVector f_row(const Eigen::SparseMatrix &M, const Eigen::VectorXd &vec, Rcpp::XPtr &SC) { - int sz = M.rows(); - SC->buildSolver(M.transpose(), "mt"); - Eigen::VectorXd row_vec = Eigen::VectorXd::Zero(sz); - row_vec(row-1) = 1; - - Eigen::VectorXd res = SC->solver().solve(row_vec); + Eigen::VectorXd res = SC->solver().solve(vec); return Rcpp::wrap(res); } // [[Rcpp::export(".f_row_iter")]] -Rcpp::NumericVector f_row_iter(Eigen::SparseMatrix &M, const int row) +Rcpp::NumericVector f_row_iter(Eigen::SparseMatrix &M, const Eigen::VectorXd &vec) { - int sz = M.rows(); Eigen::BiCGSTAB, Eigen::IncompleteLUT > solver; solver.compute(M.transpose()); - Eigen::VectorXd row_vec = Eigen::VectorXd::Zero(sz); - row_vec(row-1) = 1; - - Eigen::VectorXd res = solver.solve(row_vec); + Eigen::VectorXd res = solver.solve(vec); return Rcpp::wrap(res); } // [[Rcpp::export(".f_col")]] -Rcpp::NumericVector f_col(Eigen::Map > &M, const int col, Rcpp::XPtr &SC) +Rcpp::NumericVector f_col(Eigen::Map > &M, const Eigen::VectorXd &vec, Rcpp::XPtr &SC) { int sz = M.rows(); @@ -124,11 +88,8 @@ Rcpp::NumericVector f_col(Eigen::Map > &M, const int SC->buildSolver(M, "m"); //timer.step("compute() end"); - Eigen::VectorXd col_vec = Eigen::VectorXd::Zero(sz); - col_vec(col-1) = 1; - //timer.step("solve() start"); - Eigen::VectorXd res = SC->solver().solve(col_vec); + Eigen::VectorXd res = SC->solver().solve(vec); //timer.step("solve() end"); //Rcpp::NumericVector tr(timer); @@ -138,7 +99,7 @@ Rcpp::NumericVector f_col(Eigen::Map > &M, const int } // [[Rcpp::export(".f_col_iter")]] -Rcpp::NumericVector f_col_iter(Eigen::Map > &M, const int col) +Rcpp::NumericVector f_col_iter(Eigen::Map > &M, const Eigen::VectorXd &vec) { int sz = M.rows(); @@ -150,11 +111,8 @@ Rcpp::NumericVector f_col_iter(Eigen::Map > &M, cons solver.compute(M); //timer.step("compute() end"); - Eigen::VectorXd col_vec = Eigen::VectorXd::Zero(sz); - col_vec(col-1) = 1; - //timer.step("solve() start"); - Eigen::VectorXd res = solver.solve(col_vec); + Eigen::VectorXd res = solver.solve(vec); //timer.step("solve() end"); //Rcpp::NumericVector tr(timer); @@ -163,24 +121,4 @@ Rcpp::NumericVector f_col_iter(Eigen::Map > &M, cons return Rcpp::wrap(res); } -// [[Rcpp::export(".psif")]] -Rcpp::NumericVector psif(Eigen::Map > &M, Eigen::VectorXd &psi, Rcpp::XPtr &SC) -{ - SC->buildSolver(M.transpose(), "mt"); - - Eigen::VectorXd res = SC->solver().solve(psi); - return Rcpp::wrap(res); -} - -// [[Rcpp::export(".psif_iter")]] -Rcpp::NumericVector psif_iter(Eigen::Map > &M, Eigen::VectorXd &psi) -{ - Eigen::BiCGSTAB, Eigen::IncompleteLUT > solver; - - solver.compute(M.transpose()); - - Eigen::VectorXd res = solver.solve(psi); - - return Rcpp::wrap(res); -} diff --git a/tests/testthat/test-cond_passage.R b/tests/testthat/test-cond_passage.R index 7b0aa7d..445a09d 100644 --- a/tests/testthat/test-cond_passage.R +++ b/tests/testthat/test-cond_passage.R @@ -62,7 +62,6 @@ for(test in testlist) { }) test_that(paste("Testing cond_passage(samc, origin, dest)", test_num), { - vector_result <- cond_passage(samc_p, origin = row_vec, dest = col_vec) vector_result_char <- cond_passage(samc_p, origin = as.character(row_vec), dest = as.character(col_vec)) diff --git a/vignettes/article-circuit-theory.Rmd b/vignettes/article-circuit-theory.Rmd index 5d2b775..67e6325 100644 --- a/vignettes/article-circuit-theory.Rmd +++ b/vignettes/article-circuit-theory.Rmd @@ -2,6 +2,7 @@ title: "Circuit Theory" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Circuit Theory} diff --git a/vignettes/article-computation-methods.Rmd b/vignettes/article-computation-methods.Rmd index 674c504..ba367f5 100644 --- a/vignettes/article-computation-methods.Rmd +++ b/vignettes/article-computation-methods.Rmd @@ -2,6 +2,7 @@ title: "Computation Methods" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Computation Methods} @@ -96,7 +97,6 @@ samc_obj$method = "iter" *Weaknesses:* - Not supported for all metrics -- Metrics can only be calculated using the `init` parameter (not `origin` or `dest` inputs, but this will be partially addressed in the future) - `NA` values not supported in map inputs - Cannot define custom transition functions - Not supported for correlated random-walk (addressable in the future) diff --git a/vignettes/article-models.Rmd b/vignettes/article-models.Rmd index 33c4b34..bc1a8fe 100644 --- a/vignettes/article-models.Rmd +++ b/vignettes/article-models.Rmd @@ -2,6 +2,7 @@ title: "Models" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Models} @@ -18,14 +19,14 @@ knitr::opts_chunk$set( ## Background -The samc package currently supports two different models: random-walk (RW) and correlated random-walk (CRW). The random-walk is the default model that always has been used by the package. Version 3 made breaking changes to the samc() function to setup a structure for specifying different models, and the correlated random-walk model is the first alternative to make use of this starting with version 3.1. +The samc package currently supports a random-walk (RW) model. The random-walk is the default model that always has been used by the package. Version 3 made breaking changes to the samc() function to setup a structure for specifying different models, with plans for a correlated random-walk model in the future. ## Models Models in the samc package are defined as a list with various components depending on the context: ``` -list(name, fun, dir, sym, dist, kappa) +list(name, fun, dir, sym) ``` ### Random-Walk @@ -37,35 +38,6 @@ The basic random-walk is the default model used by the package and uses the foll - `dir` can be either `4` or `8` - `sym` can be either `TRUE` or `FALSE`, and is used as an optimization when calculating transition probabilities. -### Correlated Random-Walk - -*The correlated random-walk features are currently experimental. They may not work in all situations and are subject to change.* - -The correlated random-walk uses the same properties as the RW: - -- `name`: must be set to `"CRW"` -- `fun`: a function for calculating transition probabilities from the data input. -- `dir` can be either `4` or `8` -- `sym` can be either `TRUE` or `FALSE`, and is used as an optimization when calculating transition probabilities. - -To describe the correlated random-walk behavior, additional parameters are needed to describe the turning behavior: - -- `dist` specifies the name of a distribution or function. Currently, only `"vonMises"` is supported. -- `kappa` is specific to the von Mises distribution. It is a single number greater than or equal to `0` that sets a global turning probability. - -As the capabilities of the correlated random-walk are expanded in future updates, additional options will be documented here. - -To run metrics using the CRW, a single origin and direction value must be supplied in a 1x2 matrix (subject to change). The direction is an integer in the range 1-8 with the directions illustrated as follows: - -``` -1 2 3 -4 5 -6 7 8 -``` - -For example, `1` is up and left, while `6` is down and left. - -Support for multiple `origin` values, `init` maps, and `dest` values is not currently implemented, but will be available future releases once the CRW implementation details are finalized. ## Examples @@ -80,31 +52,15 @@ abs_data <- samc::rasterize(example_toy_res * 0 + 0.05) plot(res_data, main = "Resistance") rw_model <- list(fun = "1/mean(x)", dir = 8, sym = TRUE) -crw_model0 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 0) # Effectively a random walk after the first step -crw_model1 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 1) # Some bias against turning -crw_model2 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 2) # Moderate bias against turning -crw_model8 <- list(name = "CRW", fun = "1/mean(x)", dir = 8, sym = TRUE, dist = "vonMises", kappa = 8) # Very strong bias against turning samc_rw <- samc(res_data, abs_data, model = rw_model) -samc_crw0 <- samc(res_data, abs_data, model = crw_model0) -samc_crw1 <- samc(res_data, abs_data, model = crw_model1) -samc_crw2 <- samc(res_data, abs_data, model = crw_model2) -samc_crw8 <- samc(res_data, abs_data, model = crw_model8) origin = 85 # Centered near the bottom dir = 1 # Up and left vis_rw <- as.vector(visitation(samc_rw, origin = origin)) -vis_crw0 <- as.vector(visitation(samc_crw0, origin = matrix(c(origin, dir), 1))) -vis_crw1 <- as.vector(visitation(samc_crw1, origin = matrix(c(origin, dir), 1))) -vis_crw2 <- as.vector(visitation(samc_crw2, origin = matrix(c(origin, dir), 1))) -vis_crw8 <- as.vector(visitation(samc_crw8, origin = matrix(c(origin, dir), 1))) - +# The RW results plot(map(samc_rw, vis_rw), col = viridis(1024), main = "RW") -plot(map(samc_crw0, vis_crw0), col = viridis(1024), main = "CRW (kappa=0)") -plot(map(samc_crw1, vis_crw1), col = viridis(1024), main = "CRW (kappa=1)") -plot(map(samc_crw2, vis_crw2), col = viridis(1024), main = "CRW (kappa=2)") -plot(map(samc_crw8, vis_crw8), col = viridis(1024), main = "CRW (kappa=8)") ``` diff --git a/vignettes/code-snippets.Rmd b/vignettes/code-snippets.Rmd index 4972965..8952812 100644 --- a/vignettes/code-snippets.Rmd +++ b/vignettes/code-snippets.Rmd @@ -2,6 +2,7 @@ title: "Code Snippets" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Code Snippets} diff --git a/vignettes/data-disconnected.Rmd b/vignettes/data-disconnected.Rmd index d239172..de7f706 100644 --- a/vignettes/data-disconnected.Rmd +++ b/vignettes/data-disconnected.Rmd @@ -2,6 +2,7 @@ title: "Disconnected Data" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Disconnected Data} diff --git a/vignettes/example-coinflip.Rmd b/vignettes/example-coinflip.Rmd index 2c5c4ee..1e2bd08 100644 --- a/vignettes/example-coinflip.Rmd +++ b/vignettes/example-coinflip.Rmd @@ -2,6 +2,7 @@ title: "Coin Flip" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Coin Flip} diff --git a/vignettes/example-maze-part1.Rmd b/vignettes/example-maze-part1.Rmd index 7b6fb2c..870f43f 100644 --- a/vignettes/example-maze-part1.Rmd +++ b/vignettes/example-maze-part1.Rmd @@ -2,6 +2,7 @@ title: "Maze Part 1" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Maze Part 1} diff --git a/vignettes/example-maze-part2.Rmd b/vignettes/example-maze-part2.Rmd index 3a69bfd..03ffd42 100644 --- a/vignettes/example-maze-part2.Rmd +++ b/vignettes/example-maze-part2.Rmd @@ -2,6 +2,7 @@ title: "Maze Part 2" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Maze Part 2} diff --git a/vignettes/example-maze-part3.Rmd b/vignettes/example-maze-part3.Rmd index dba3b38..9cfed0e 100644 --- a/vignettes/example-maze-part3.Rmd +++ b/vignettes/example-maze-part3.Rmd @@ -2,6 +2,7 @@ title: "Maze Part 3" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Maze Part 3} diff --git a/vignettes/overview.Rmd b/vignettes/overview.Rmd index f74ae8e..ca99624 100644 --- a/vignettes/overview.Rmd +++ b/vignettes/overview.Rmd @@ -2,6 +2,7 @@ title: "Overview" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Overview} diff --git a/vignettes/parallel.Rmd b/vignettes/parallel.Rmd index 253b87a..56820a7 100644 --- a/vignettes/parallel.Rmd +++ b/vignettes/parallel.Rmd @@ -2,6 +2,7 @@ title: "Parallel Computing" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Parallel Computing} diff --git a/vignettes/performance.Rmd b/vignettes/performance.Rmd index 220fede..4010f54 100644 --- a/vignettes/performance.Rmd +++ b/vignettes/performance.Rmd @@ -2,6 +2,7 @@ title: "Performance" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Performance} diff --git a/vignettes/scripts/example-coinflip.R b/vignettes/scripts/example-coinflip.R index b45d83a..a7b459d 100644 --- a/vignettes/scripts/example-coinflip.R +++ b/vignettes/scripts/example-coinflip.R @@ -1,5 +1,5 @@ -# Copyright (c) 2022 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. # This script is the source of the code for the coin flip example vignette # The lines with `@knitr` are for processing by knitr diff --git a/vignettes/scripts/example-maze.R b/vignettes/scripts/example-maze.R index bdc786b..45c7968 100644 --- a/vignettes/scripts/example-maze.R +++ b/vignettes/scripts/example-maze.R @@ -1,5 +1,5 @@ -# Copyright (c) 2021 Andrew Marx. All rights reserved. -# Licensed under GPLv3.0. See LICENSE file in the project root for details. +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. # This script is the source of the code for maze example vignettes # The lines with `@knitr` are for processing by knitr diff --git a/vignettes/scripts/tutorial-animations.R b/vignettes/scripts/tutorial-animations.R index a09c127..7c79e6f 100644 --- a/vignettes/scripts/tutorial-animations.R +++ b/vignettes/scripts/tutorial-animations.R @@ -1,3 +1,6 @@ +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. + # This script is the source of the code for the animations vignette and is also # used to generate the output figures. It only needs to be run directly if changes # to the figures are desired diff --git a/vignettes/scripts/tutorial-ggplot.R b/vignettes/scripts/tutorial-ggplot.R index 7fdf6f2..36e1906 100644 --- a/vignettes/scripts/tutorial-ggplot.R +++ b/vignettes/scripts/tutorial-ggplot.R @@ -1,3 +1,6 @@ +# Copyright (c) 2024 Andrew Marx. All rights reserved. +# Licensed under AGPLv3.0. See LICENSE file in the project root for details. + # This script is the source of the code for the ggplot vignette and is also used # to generate the output figures. It only needs to be run directly if changes to # the figures are desired diff --git a/vignettes/troubleshooting.Rmd b/vignettes/troubleshooting.Rmd index a76d588..73231d3 100644 --- a/vignettes/troubleshooting.Rmd +++ b/vignettes/troubleshooting.Rmd @@ -2,6 +2,7 @@ title: "Troubleshooting" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Troubleshooting} diff --git a/vignettes/tutorial-animations.Rmd b/vignettes/tutorial-animations.Rmd index 6be1437..2dee74c 100644 --- a/vignettes/tutorial-animations.Rmd +++ b/vignettes/tutorial-animations.Rmd @@ -2,6 +2,7 @@ title: "Animations" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Animations} diff --git a/vignettes/tutorial-basic.Rmd b/vignettes/tutorial-basic.Rmd index 2b40f16..00ce160 100644 --- a/vignettes/tutorial-basic.Rmd +++ b/vignettes/tutorial-basic.Rmd @@ -2,6 +2,7 @@ title: "Basic Tutorial" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Basic Tutorial} diff --git a/vignettes/tutorial-ggplot.Rmd b/vignettes/tutorial-ggplot.Rmd index 5b15804..9503eff 100644 --- a/vignettes/tutorial-ggplot.Rmd +++ b/vignettes/tutorial-ggplot.Rmd @@ -2,6 +2,7 @@ title: "ggplot Visualization" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{ggplot Visualization} diff --git a/vignettes/tutorial-locations.Rmd b/vignettes/tutorial-locations.Rmd index 9c1fab0..04c9168 100644 --- a/vignettes/tutorial-locations.Rmd +++ b/vignettes/tutorial-locations.Rmd @@ -2,6 +2,7 @@ title: "Locations" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Locations} diff --git a/vignettes/tutorial-multiple-absorption.Rmd b/vignettes/tutorial-multiple-absorption.Rmd index e3bf0c8..1f9f3a4 100644 --- a/vignettes/tutorial-multiple-absorption.Rmd +++ b/vignettes/tutorial-multiple-absorption.Rmd @@ -2,6 +2,7 @@ title: "Multiple Absorption Tutorial" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Multiple Absorption Tutorial} diff --git a/vignettes/tutorial-temporal.Rmd b/vignettes/tutorial-temporal.Rmd index f3aad21..5636c35 100644 --- a/vignettes/tutorial-temporal.Rmd +++ b/vignettes/tutorial-temporal.Rmd @@ -2,6 +2,7 @@ title: "Temporal Analysis" author: "Andrew Marx" date: "`r Sys.Date()`" +license: "CC BY-NC-SA 4.0" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Temporal Analysis}