diff --git a/.Rbuildignore b/.Rbuildignore
index f2dea5f..a63e6f2 100644
--- a/.Rbuildignore
+++ b/.Rbuildignore
@@ -1 +1,2 @@
^data-raw$
+^\.github$
\ No newline at end of file
diff --git a/DESCRIPTION b/DESCRIPTION
index ce62d24..4ffb083 100644
--- a/DESCRIPTION
+++ b/DESCRIPTION
@@ -1,16 +1,20 @@
Package: dsem
Type: Package
Title: Fit Dynamic Structural Equation Models
-Version: 1.0
-Date: 2023-06-21
+Version: 1.0.0
+Date: 2023-12-04
Authors@R:
- c(person(given = "Anon",
- family = "Ymous",
+ c(person(given = "James",
+ family = "Thorson",
role = c("aut", "cre"),
email = "James.Thorson@noaa.gov")
)
Imports:
- TMB,
+ TMB (>= 1.9.7),
+ Matrix (>= 1.6.3),
+ sem,
+ igraph,
+ methods
Depends:
R (>= 4.0.0),
Suggests:
@@ -18,19 +22,27 @@ Suggests:
AER,
phylopath,
rmarkdown,
+ reshape,
+ gridExtra,
dynlm,
MARSS,
ggplot2,
ggpubr,
+ ggraph,
grid,
vars,
testthat
+Enhances:
+ rstan,
+ tmbstan
LinkingTo:
TMB,
RcppEigen
Description: Applies dynamic structural equation models to time-series data
with generic and simplified specification for simultaneous and lagged
- effects.
+ effects. Methods are described in Thorson et al. (In revision)
+ "Dynamic structural equation models synthesize ecosystem dynamics
+ constrained by ecological mechanisms."
License: GPL-3
Encoding: UTF-8
RoxygenNote: 7.2.3
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..9cecc1d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {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 General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/NAMESPACE b/NAMESPACE
index a98c022..cb7a24b 100644
--- a/NAMESPACE
+++ b/NAMESPACE
@@ -1,23 +1,35 @@
# Generated by roxygen2: do not edit by hand
S3method(logLik,dsem)
+S3method(plot,dsem)
S3method(predict,dsem)
+S3method(print,dsem)
S3method(residuals,dsem)
S3method(simulate,dsem)
S3method(summary,dsem)
S3method(vcov,dsem)
export(TMBAIC)
export(as_fitted_DAG)
+export(as_sem)
export(classify_variables)
export(dsem)
+export(dsem_control)
export(fit_tmb)
export(list_parameters)
-export(make_ram)
+export(make_dsem_ram)
+export(parse_path)
+importFrom(Matrix,Cholesky)
+importFrom(Matrix,solve)
importFrom(TMB,MakeADFun)
importFrom(TMB,compile)
importFrom(TMB,dynlib)
importFrom(TMB,sdreport)
importFrom(TMB,summary.sdreport)
+importFrom(igraph,graph_from_data_frame)
+importFrom(igraph,plot.igraph)
+importFrom(methods,is)
+importFrom(sem,sem)
+importFrom(stats,"tsp<-")
importFrom(stats,.preformat.ts)
importFrom(stats,logLik)
importFrom(stats,na.omit)
@@ -25,5 +37,7 @@ importFrom(stats,nlminb)
importFrom(stats,optimHess)
importFrom(stats,pnorm)
importFrom(stats,rnorm)
+importFrom(stats,simulate)
+importFrom(stats,time)
importFrom(stats,vcov)
useDynLib(dsem, .registration = TRUE)
diff --git a/R/classify_variables.R b/R/classify_variables.R
index 03950ef..54a0aa6 100644
--- a/R/classify_variables.R
+++ b/R/classify_variables.R
@@ -1,9 +1,10 @@
-#' Classify variables path
+#' @title Classify variables path
#'
-#' \code{classify_variables} is copied from \code{sem:::classifyVariables}
+#' @description \code{classify_variables} is copied from \code{sem:::classifyVariables}
#'
-#' Copied with permission from John Fox under licence GPL (>= 2)
+#' @details
+#' Copied from package `sem` under licence GPL (>= 2) with permission from John Fox
#'
#' @param model SEM model
#'
diff --git a/R/data.R b/R/data.R
index 0911a0f..612c097 100644
--- a/R/data.R
+++ b/R/data.R
@@ -19,10 +19,20 @@ NULL
#' @keywords data
NULL
-#' Isle Royale wolf and moose
+#' @title Isle Royale wolf and moose
#'
+#' @description
#' Data used to demonstrate and test cross-lagged (vector autoregressive) models
#'
+#' @details
+#' Data extracted from file "Data_wolves_moose_Isle_Royale_June2019.csv" available at
+#' \url{https://isleroyalewolf.org/data/data/home.html} and obtained 2023-06-23.
+#' Reproduced with permission from John Vucetich, and generated by the
+#' Wolves and Moose of Isle Royale project.
+#'
+#' @references
+#' Vucetich, JA and Peterson RO. 2012. The population biology of Isle Royale wolves and moose: an overview. \url{https://www.isleroyalewolf.org}
+#'
#' @name isle_royale
#' @docType data
#' @usage data(isle_royale)
diff --git a/R/dsem.R b/R/dsem.R
index dfcb013..d311129 100644
--- a/R/dsem.R
+++ b/R/dsem.R
@@ -1,10 +1,10 @@
-#' Fit dynamic structural equation model
+#' @title Fit dynamic structural equation model
#'
-#' Fits a dynamic structural equation model
+#' @description Fits a dynamic structural equation model
#'
-#' @param sem structural equation model structure, passed to either \code{\link[sem]{specifyModel}}
-#' or \code{\link[sem]{specifyEquations}} and then parsed to control
-#' the set of path coefficients and variance-covariance parameters
+#' @param sem Specification for time-series structural equation model structure
+#' including lagged or simultaneous effects. See Details section in
+#' \code{\link[dsem]{make_dsem_ram}} for more description
#' @param tsdata time-series data, as outputted using \code{\link[stats]{ts}}
#' @param family Character-vector listing the distribution used for each column of \code{tsdata}, where
#' each element must be \code{fixed} or \code{normal}.
@@ -13,27 +13,53 @@
#' @param estimate_delta0 Boolean indicating whether to estimate deviations from equilibrium in initial year
#' as fixed effects, or alternatively to assume that dynamics start at some stochastic draw away from
#' the stationary distribution
-#' @param run_model Boolean indicating whether to estimate parameters (the default), or
-#' instead to return the model inputs and compiled TMB object without running;
-#' @param quiet Boolean indicating whether to run model printing messages to terminal or not;
-#' @param use_REML Boolean indicating whether to treat non-variance fixed effects as random,
-#' either to motigate bias in estimated variance parameters or improve efficiency for
-#' parameter estimation given correlated fixed and random effects
-#' @param parameters list of fixed and random effects, e.g., as constructed by \code{dsem} and then modified
-#' by hand (only helpful for advanced users to change starting values or restart at intended values)
-#' @param map list of fixed and mirrored parameters, constructed by \code{dsem} by default but available
-#' to override this default and then pass to \code{\link[TMB]{MakeADFun}}
+#' @param control Output from \code{\link{dsem_control}}, used to define user
+#' settings, and see documentation for that function for details.
#' @param ... Additional parameters passed to \code{\link{fit_tmb}}
#'
#' @importFrom TMB compile dynlib MakeADFun sdreport summary.sdreport
-#' @importFrom stats .preformat.ts na.omit nlminb optimHess pnorm rnorm
+#' @importFrom stats .preformat.ts na.omit nlminb optimHess pnorm rnorm simulate time tsp<-
+#' @importFrom Matrix solve Cholesky
+#' @importFrom sem sem
+#' @importFrom igraph plot.igraph graph_from_data_frame
+#' @importFrom methods is
+#'
+#' @details
+#' A DSEM involves (at a minimum):
+#' \describe{
+#' \item{Time series}{a matrix \eqn{\mathbf X} where column \eqn{\mathbf x_c} for variable c is
+#' a time-series;}
+#' \item{Path diagram}{a user-supplied specification for the path coefficients, which
+#' define the precision (inverse covariance) \eqn{\mathbf Q} for a matrix of state-variables
+#' and see \code{\link{make_dsem_ram}} for more details on the math involved.}
+#' }
+#' The model also estimates the time-series mean \eqn{ \mathbf{\mu}_c } for each variable.
+#' The mean and precision matrix therefore define a Gaussian Markov random field for \eqn{\mathbf X}:
+#'
+#' \deqn{ \mathrm{vec}(\mathbf X) \sim \mathrm{MVN}( \mathrm{vec}(\mathbf{I_T} \otimes \mathbf{\mu}), \mathbf{Q}^{-1}) }
+#'
+#' Users can the specify
+#' a distribution for measurement errors (or assume that variables are measured without error) using
+#' argument \code{family}. This defines the link-function \eqn{g_c(.)} and distribution \eqn{f_c(.)}
+#' for each time-series \eqn{c}:
+#'
+#' \deqn{ y_{t,c} \sim f_c( g_c^{-1}( x_{t,c} ), \theta_c )}
+#'
+#' \code{dsem} then estimates all specified coefficients, time-series means \eqn{\mu_c}, and distribution
+#' measurement errors \eqn{\theta_c} via maximizing a log-marginal likelihood, while
+#' also estimating state-variables \eqn{x_{t,c}}.
+#' \code{summary.dsem} then assembles estimates and standard errors in an easy-to-read format.
+#' Standard errors for fixed effects (path coefficients, exogenoux variance parameters, and measurement error parameters)
+#' are estimated from the matrix of second derivatives of the log-marginal likelihod,
+#' and standard errors for random effects (i.e., missing or state-space variables) are estimated
+#' from a generalization of this method (see \code{\link[TMB]{sdreport}} for details).
#'
#' @return
#' An object (list) of class `dsem`. Elements include:
#' \describe{
#' \item{obj}{TMB object from \code{\link[TMB]{MakeADFun}}}
-#' \item{ram}{RAM parsed by \code{make_ram}}
-#' \item{model}{SEM model parsed from \code{sem} using \code{\link[sem]{specifyModel}} or \code{\link[sem]{specifyEquations}}}
+#' \item{ram}{RAM parsed by \code{make_dsem_ram}}
+#' \item{model}{SEM structure parsed by \code{make_dsem_ram} as intermediate description of model linkages}
#' \item{tmb_inputs}{The list of inputs passed to \code{\link[TMB]{MakeADFun}}}
#' \item{opt}{The output from \code{\link{fit_tmb}}}
#' }
@@ -50,62 +76,34 @@
#' @examples
#' # Define model
#' sem = "
-#' Profits -> Consumption, 0, a2
-#' Profits -> Consumption, -1, a3
-#' Priv_wage -> Consumption, 0, a4
-#' Gov_wage -> Consumption, 0, a4
-#' Consumption <-> Consumption, 0, v1
-#' Consumption -> Consumption, -1, ar1
-#' Consumption -> Consumption, -2, ar2
-#' Profits -> Investment, 0, b2
-#' Profits -> Investment, -1, b3
-#' Capital_stock -> Investment, -1, b4
-#' Investment <-> Investment, 0, v2
-#' neg_Gov_wage <-> neg_Gov_wage, 0, v3
-#' GNP -> Priv_wage, 0, c2
-#' Taxes -> Priv_wage, 0, c2
-#' neg_Gov_wage -> Priv_wage, 0, c2
-#' GNP -> Priv_wage, -1, c3
-#' Taxes -> Priv_wage, -1, c3
-#' neg_Gov_wage -> Priv_wage, -1, c3
-#' Time -> Priv_wage, 0, c4
-#' Priv_wage <-> Priv_wage, 0, v4
-#' GNP <-> GNP, 0, v5
-#' Profits <-> Profits, 0, v6
-#' Capital_stock <-> Capital_stock, 0, v7
-#' Taxes <-> Taxes, 0, v8
-#' Time <-> Time, 0, v9
-#' Gov_wage <-> Gov_wage, 0, v10
-#' Gov_expense <-> Gov_expense, 0, v11
+#' # Link, lag, param_name
+#' cprofits -> consumption, 0, a1
+#' cprofits -> consumption, 1, a2
+#' pwage -> consumption, 0, a3
+#' gwage -> consumption, 0, a3
+#' cprofits -> invest, 0, b1
+#' cprofits -> invest, 1, b2
+#' capital -> invest, 0, b3
+#' gnp -> pwage, 0, c2
+#' gnp -> pwage, 1, c3
+#' time -> pwage, 0, c1
#' "
#'
#' # Load data
#' data(KleinI, package="AER")
-#' Data = as.data.frame(KleinI)
-#' Data = cbind( Data, "time" = seq(1,22)-11 )
-#' colnames(Data) = sapply( colnames(Data), FUN=switch,
-#' "consumption"="Consumption", "invest"="Investment",
-#' "cprofits"="Profits", "capital"="Capital_stock", "gwage"="Gov_wage",
-#' "pwage"="Priv_wage", "gexpenditure"="Gov_expense", "taxes"="Taxes",
-#' "time"="Time", "gnp"="GNP")
-#' Z = ts( cbind(Data, "neg_Gov_wage"=-1*Data[,'Gov_wage']) )
+#' TS = ts(data.frame(KleinI, "time"=time(KleinI) - 1931))
+#' tsdata = TS[,c("time","gnp","pwage","cprofits",'consumption',
+#' "gwage","invest","capital")]
#'
#' # Fit model
-#' fit = dsem( sem=sem, tsdata=Z )
+#' fit = dsem( sem=sem,
+#' tsdata = tsdata,
+#' newtonsteps = 0,
+#' estimate_delta0 = TRUE,
+#' control = dsem_control(quiet=TRUE) )
#' summary( fit )
-#'
-#' # Plot results
-#' library(ggplot2)
-#' library(ggpubr)
-#' library(phylopath)
-#' p1 = plot(as_fitted_DAG(fit), text_size=3, type="width", show.legend=FALSE)
-#' p1$layers[[1]]$mapping$edge_width = 0.5
-#' p2 = plot(as_fitted_DAG(fit, lag=-1), text_size=3, type="width", show.legend=FALSE)
-#' p2$layers[[1]]$mapping$edge_width = 0.25
-#' ggarrange(p1 + scale_x_continuous(expand = c(0.2, 0.0)),
-#' p2 + scale_x_continuous(expand = c(0.2, 0.0)),
-#' labels = c("Simultaneous effects", "Lag-1 effects"),
-#' ncol = 1, nrow = 2)
+#' plot( fit )
+#' plot( fit, edge_label="value" )
#'
#' @useDynLib dsem, .registration = TRUE
#' @export
@@ -113,17 +111,18 @@ dsem <-
function( sem,
tsdata,
family = rep("fixed",ncol(tsdata)),
- covs = colnames(tsdata),
estimate_delta0 = FALSE,
- quiet = FALSE,
- run_model = TRUE,
- use_REML = TRUE,
- parameters = NULL,
- map = NULL,
+ control = dsem_control(),
... ){
+ # General error checks
+ if( isFALSE(is(control, "dsem_control")) ) stop("`control` must be made by `dsem_control()`")
+
# (I-Rho)^-1 * Gamma * (I-Rho)^-1
- out = make_ram( sem, tsdata=tsdata, quiet=quiet, covs=covs )
+ out = make_dsem_ram( sem,
+ times = as.numeric(time(tsdata)),
+ variables = colnames(tsdata),
+ quiet = control$quiet )
ram = out$ram
# Error checks
@@ -141,7 +140,7 @@ function( sem,
"y_tj" = tsdata )
# Construct parameters
- if( is.null(parameters) ){
+ if( is.null(control$parameters) ){
Params = list( "beta_z" = rep(0,max(ram[,4])),
"lnsigma_j" = rep(0,ncol(tsdata)),
"mu_j" = rep(0,ncol(tsdata)),
@@ -163,11 +162,11 @@ function( sem,
start_z = tapply( as.numeric(ram[which_nonzero,5]), INDEX=ram[which_nonzero,4], mean )
Params$beta_z = ifelse( is.na(start_z), Params$beta_z, start_z)
}else{
- Params = parameters
+ Params = control$parameters
}
# Construct map
- if( is.null(map) ){
+ if( is.null(control$map) ){
Map = list()
Map$x_tj = factor(ifelse( is.na(as.vector(tsdata)) | (Data$familycode_j[col(tsdata)] %in% c(1,2,3,4)), seq_len(prod(dim(tsdata))), NA ))
Map$lnsigma_j = factor( ifelse(Data$familycode_j==0, NA, seq_along(Params$lnsigma_j)) )
@@ -175,17 +174,17 @@ function( sem,
# Map off mean for latent variables
Map$mu_j = factor( ifelse(colSums(!is.na(tsdata))==0, NA, 1:ncol(tsdata)) )
}else{
- Map = map
+ Map = control$map
}
# Initial run
- if(isTRUE(use_REML)){
+ if(isTRUE(control$use_REML)){
Random = c( "x_tj", "mu_j" )
}else{
Random = "x_tj"
}
obj = MakeADFun( data=Data, parameters=Params, random=Random, map=Map, DLL="dsem" )
- if(quiet==FALSE) list_parameters(obj)
+ if(control$quiet==FALSE) list_parameters(obj)
out = list( "obj"=obj,
"ram"=ram,
"sem_full"=out$model,
@@ -193,15 +192,15 @@ function( sem,
"call" = match.call() )
# Export stuff
- if( run_model==FALSE ){
+ if( control$run_model==FALSE ){
return( out )
}
# Fit
obj$env$beSilent() # if(!is.null(Random))
out$opt = fit_tmb( obj,
- quiet = quiet,
- control = list(eval.max=10000, iter.max=10000, trace=ifelse(quiet==TRUE,0,1) ),
+ quiet = control$quiet,
+ control = list(eval.max=10000, iter.max=10000, trace=ifelse(control$quiet==TRUE,0,1) ),
... )
# output
@@ -209,20 +208,95 @@ function( sem,
return(out)
}
-#' summarize dsem
+#' @title Detailed control for dsem structure
#'
-#' @title Summarize dsem
+#' @description Define a list of control parameters. Note that
+#' the format of this input is likely to change more rapidly than that of
+#' \code{\link{dsem}}
+#'
+#' @param run_model Boolean indicating whether to estimate parameters (the default), or
+#' instead to return the model inputs and compiled TMB object without running;
+#' @param quiet Boolean indicating whether to run model printing messages to terminal or not;
+#' @param use_REML Boolean indicating whether to treat non-variance fixed effects as random,
+#' either to motigate bias in estimated variance parameters or improve efficiency for
+#' parameter estimation given correlated fixed and random effects
+#' @param parameters list of fixed and random effects, e.g., as constructed by \code{dsem} and then modified
+#' by hand (only helpful for advanced users to change starting values or restart at intended values)
+#' @param map list of fixed and mirrored parameters, constructed by \code{dsem} by default but available
+#' to override this default and then pass to \code{\link[TMB]{MakeADFun}}
+#'
+#' @return
+#' An S3 object of class "dsem_control" that specifies detailed model settings,
+#' allowing user specification while also specifying default values
+#'
+#' @export
+dsem_control <-
+function( quiet = FALSE,
+ run_model = TRUE,
+ use_REML = TRUE,
+ parameters = NULL,
+ map = NULL ){
+
+ # Return
+ structure( list(
+ quiet = quiet,
+ run_model = run_model,
+ use_REML = use_REML,
+ parameters = parameters,
+ map = map
+ ), class = "dsem_control" )
+}
+
+#' @title summarize dsem
+#'
+#' @description summarize parameters from a fitted dynamic structural equation model
+#'
+#' @details
+#' A DSEM is specified using "arrow and lag" notation, which specifies the set of
+#' path coefficients and exogenous variance parameters to be estimated. Function \code{dsem}
+#' then estimates the maximum likelihood value for those coefficients and parameters
+#' by maximizing the log-marginal likelihood. Standard errors for parameters are calculated
+#' from the matrix of second derivatives of this log-marginal likelihood (the "Hessian matrix").
+#'
+#' However, many users will want to associate individual parameters and standard errors
+#' with the path coefficients that were specified using the "arrow and lag" notation.
+#' This task is complicated in
+#' models where some path coefficients or variance parameters are specified to share a single value a priori,
+#' or were assigned a name of NA and hence assumed to have a fixed value a priori (such that
+#' these coefficients or parameters have an assigned value but no standard error).
+#' The \code{summary} function therefore compiles the MLE for coefficients (including duplicating
+#' values for any path coefficients that assigned the same value) and standard error
+#' estimates, and outputs those in a table that associates them with the user-supplied path and parameter names.
+#' It also outputs the z-score and a p-value arising from a two-sided Wald test (i.e.
+#' comparing the estimate divided by standard error against a standard normal distribution).
#'
#' @param object Output from \code{\link{dsem}}
#' @param ... Not used
#'
+#' @return
+#' Returns a data.frame summarizing estimated path coefficients, containing columns:
+#' \describe{
+#' \item{path}{The parsed path coefficient}
+#' \item{lag}{The lag, where e.g. 1 means the predictor in time t effects the response in time t+1}
+#' \item{name}{Parameter name}
+#' \item{start}{Start value if supplied, and NA otherwise}
+#' \item{parameter}{Parameter number}
+#' \item{first}{Variable in path treated as predictor}
+#' \item{second}{Variable in path treated as response}
+#' \item{direction}{Whether the path is one-headed or two-headed}
+#' \item{Estimate}{Maximum likelihood estimate}
+#' \item{Std_Error}{Estimated standard error from the Hessian matrix}
+#' \item{z_value}{Estimate divided by Std_Error}
+#' \item{p_value}{P-value associated with z_value using a two-sided Wald test}
+#' }
+#'
#' @method summary dsem
#' @export
summary.dsem <-
function( object, ... ){
# Easy of use
- model = object$model
+ model = object$sem_full
ParHat = object$obj$env$parList()
#
@@ -238,9 +312,56 @@ function( object, ... ){
return(coefs)
}
-#' Simulate dsem
+
+#' @title Simulate dsem
+#'
+#' @description Plot from a fitted \code{dsem} model
#'
-#' @title Simulate from a fitted \code{dsem} model
+#' @param x Output from \code{\link{dsem}}
+#' @param y Not used
+#' @param edge_label Whether to plot parameter names or estimated values
+#' @param digits integer indicating the number of decimal places to be used
+#' @param ... arguments passed to \code{\link[igraph]{plot.igraph}}
+#'
+#' @details
+#' This function coerces output from a graph and then plots the graph.
+#'
+#' @return
+#' Invisibly returns the output from \code{\link[igraph]{graph_from_data_frame}}
+#' which was passed to \code{\link[igraph]{plot.igraph}} for plotting.
+#'
+#' @method plot dsem
+#' @export
+plot.dsem <-
+function( x,
+ y,
+ edge_label = c("name","value"),
+ digits = 2,
+ ... ){
+
+ # Extract stuff
+ edge_label = match.arg(edge_label)
+ out = summary(x)
+
+ # Format inputs
+ from = ifelse( out[,2]==0, out$first, paste0("lag(",out$first,",",out[,2],")"))
+ vertices = union( out$second, from )
+ DF = data.frame(from=from, to=out$second, label=out[,3])
+ if( edge_label=="value"){
+ DF$label = round(out$Estimate, digits=digits)
+ }
+
+ # Create and plotgraph
+ pg <- graph_from_data_frame( d = DF,
+ directed = TRUE,
+ vertices = data.frame(vertices) )
+ plot( pg, ... )
+ return(invisible(pg))
+}
+
+#' @title Simulate dsem
+#'
+#' @description Simulate from a fitted \code{dsem} model
#'
#' @param object Output from \code{\link{dsem}}
#' @param nsim number of simulated data sets
@@ -252,14 +373,20 @@ function( object, ... ){
#' @param seed random seed
#' @param ... Not used
#'
-#' @description
+#' @details
#' This function conducts a parametric bootstrap, i.e., simulates new data
#' conditional upon estimated values for fixed and random effects. The user
#' can optionally simulate new random effects conditional upon their estimated
#' covariance, or simulate new fixed and random effects conditional upon their imprecision.
#'
#' Note that \code{simulate} will have no effect on states \code{x_tj} for which there
-#' is a measurement and when those measurements are fitted using \code{family="fixed"}
+#' is a measurement and when those measurements are fitted using \code{family="fixed"}, unless
+#' \code{resimulate_gmrf=TRUE}. In this latter case, the GMRF is resimulated given
+#' estimated path coefficients
+#'
+#' @return
+#' Simulated data, either from \code{obj$simulate} where \code{obj} is the compiled
+#' TMB object, first simulating a new GMRF and then calling \code{obj$simulate}.
#'
#' @method simulate dsem
#' @export
@@ -271,36 +398,40 @@ function( object,
resimulate_gmrf = FALSE,
... ){
+ # Front stuff
set.seed(seed)
variance = match.arg(variance)
# Sample from GMRF using sparse precision
rmvnorm_prec <- function(mu, prec, nsim) {
z <- matrix(rnorm(length(mu) * nsim), ncol=nsim)
- L <- Matrix::Cholesky(prec, super=TRUE)
- z <- Matrix::solve(L, z, system = "Lt") ## z = Lt^-1 %*% z
- z <- Matrix::solve(L, z, system = "Pt") ## z = Pt %*% z
+ L <- Cholesky(prec, super=TRUE)
+ z <- solve(L, z, system = "Lt") ## z = Lt^-1 %*% z
+ z <- solve(L, z, system = "Pt") ## z = Pt %*% z
z <- as.matrix(z)
return(mu + z)
}
- #
+ # pull out objects for easy use
obj = object$obj
parfull = obj$env$parList()
+ tsdata = eval(object$call$tsdata)
+ # Extract parameters, and add noise as desired
par_zr = outer( obj$env$last.par.best, rep(1,nsim) )
if( variance=="random" ){
- tmp = rmvnorm_prec( rep(0,length(obj$env$random)), obj$env$spHess(random=TRUE), nsim=nsim )
- par_zr[obj$env$random,] = par_zr[obj$env$random,,drop=FALSE] + tmp
+ eps_zr = rmvnorm_prec( rep(0,length(obj$env$random)), obj$env$spHess(random=TRUE), nsim=nsim )
+ par_zr[obj$env$random,] = par_zr[obj$env$random,,drop=FALSE] + eps_zr
}
if( variance=="both" ){
if(is.null(object$opt$SD$jointPrecision)){
stop("Please re-run `dsem` with `getsd=TRUE` and `getJointPrecision=TRUE`, or confirm that the model is converged")
}
- tmp = rmvnorm_prec( rep(0,length(obj$env$last.par)), object$opt$SD$jointPrecision, nsim=nsim )
- par_zr = par_zr + tmp
+ eps_zr = rmvnorm_prec( rep(0,length(obj$env$last.par)), object$opt$SD$jointPrecision, nsim=nsim )
+ par_zr = par_zr + eps_zr
}
+ # Simulate new GMRF and data conditional on simulated parameters
out = NULL
for( r in seq_len(nsim) ){
if( resimulate_gmrf==TRUE ){
@@ -320,26 +451,29 @@ function( object,
}else{
out[[r]] = obj$simulate( par_zr[,r] )
}
+ colnames(out[[r]]) = colnames(tsdata)
+ tsp(out[[r]]) = attr(tsdata,"tsp")
+ class(out[[r]]) = class(tsdata)
}
- #out = lapply( 1:nsim, FUN=\(x) obj$env$simulate(par=par_zr[,x],complete=TRUE)$y_tj )
- #mean( obj$env$simulate(par=par_zr[,1],complete=TRUE)$y_tj )
- #mean( obj$env$simulate(par=par_zr[,2]+1,complete=TRUE)$y_tj )
- #sapply(out, mean)
- #apply(par_zr, MARGIN=2, mean)
-
return(out)
}
-#' Extract Variance-Covariance Matrix
+#' @title Extract Variance-Covariance Matrix
#'
-#' extract the covariance of fixed effects, or both fixed and random effects.
+#' @description extract the covariance of fixed effects, or both fixed and random effects.
#'
#' @param object output from \code{dsem}
#' @param which whether to extract the covariance among fixed effects, random effects, or both
#' @param ... ignored, for method compatibility
#' @importFrom stats vcov
#' @method vcov dsem
+#'
+#' @return
+#' A square matrix containing the estimated covariances among the parameter estimates in the model.
+#' The dimensions dependend upon the argument \code{which}, to determine whether fixed, random effects,
+#' or both are outputted.
+#'
#' @export
vcov.dsem <-
function( object,
@@ -370,15 +504,20 @@ function( object,
return( V )
}
-#' Calculate residuals
+#' @title Calculate residuals
#'
-#' @title Calculate residuals for dsem
+#' @description Calculate deviance or response residuals for dsem
#'
#' @param object Output from \code{\link{dsem}}
#' @param type which type of residuals to compute (only option is \code{"deviance"} or \code{"response"} for now)
-#' @param ... Note used
+#' @param ... Not used
#'
#' @method residuals dsem
+#'
+#' @return
+#' A matrix of residuals, with same order and dimensions as argument \code{tsdata}
+#' that was passed to \code{dsem}.
+#'
#' @export
residuals.dsem <-
function( object,
@@ -447,9 +586,28 @@ function( object,
return(resid_tj)
}
-#' predictions using dsem
+#' @title Print fitted dsem object
+#'
+#' @description Prints output from fitted dsem model
+#'
+#' @param x Output from \code{\link{dsem}}
+#' @param ... Not used
+#'
+#' @return
+#' No return value, called to provide clean terminal output when calling fitted
+#' object in terminal.
+#'
+#' @method print dsem
+#' @export
+print.dsem <-
+function( x,
+ ... ){
+ print(x$opt)
+}
+
+#' @title predictions using dsem
#'
-#' @title Predict variables given new (counterfactual) values of data, or for future or past times
+#' @description Predict variables given new (counterfactual) values of data, or for future or past times
#'
#' @param object Output from \code{\link{dsem}}
#' @param newdata optionally, a data frame in which to look for variables with which to predict.
@@ -460,7 +618,14 @@ function( object,
#' @param type the type of prediction required. The default is on the scale of the linear predictors;
#' the alternative "response" is on the scale of the response variable.
#' Thus for a Poisson-distributed variable the default predictions are of log-intensity and type = "response" gives the predicted intensity.
-#' @param ... Note used
+#' @param ... Not used
+#'
+#' @return
+#' A matrix of predicted values with dimensions and order corresponding to
+#' argument \code{newdata} is provided, or \code{tsdata} if not.
+#' Predictions are provided on either link or response scale, and
+#' are generated by re-optimizing random effects condition on MLE
+#' for fixed effects, given those new data.
#'
#' @method predict dsem
#' @export
@@ -498,12 +663,24 @@ function( object,
return(out)
}
-# Extract the log-likelihood of a dsem model
-#
-# @return object of class \code{logLik} with attributes
-# \item{val}{log-likelihood}
-# \item{df}{number of parameters}
+#' @title Marglinal log-likelihood
+#'
+#' @description Extract the (marginal) log-likelihood of a dsem model
+#'
+#' @param object Output from \code{\link{dsem}}
+#' @param ... Not used
+#'
+#' @return object of class \code{logLik} with attributes
+#' \item{val}{log-likelihood}
+#' \item{df}{number of parameters}
#' @importFrom stats logLik
+#'
+#' @return
+#' Returns an object of class logLik. This has attributes
+#' "df" (degrees of freedom) giving the number of (estimated) fixed effects
+#' in the model, abd "val" (value) giving the marginal log-likelihood.
+#' This class then allows \code{AIC} to work as expected.
+#'
#' @export
logLik.dsem <- function(object, ...) {
val = -1 * object$opt$objective
@@ -522,6 +699,7 @@ logLik.dsem <- function(object, ...) {
#' @param lag which lag to output
#' @param what whether to output estimates \code{what="Estimate"}, standard errors \code{what="Std_Error"}
#' or p-values \code{what="Std_Error"}
+#' @param direction whether to include one-sided arrows \code{direction=1}, or both one- and two-sided arrows \code{direction=c(1,2)}
#'
#' @return Convert output to format supplied by \code{\link[phylopath]{est_DAG}}
#'
@@ -529,17 +707,68 @@ logLik.dsem <- function(object, ...) {
as_fitted_DAG <-
function( fit,
lag = 0,
- what = "Estimate" ){
+ what = "Estimate",
+ direction = 1 ){
coefs = summary( fit )
coefs = coefs[ which(coefs[,2]==lag), ]
- coefs = coefs[ which(coefs[,'direction']==1), ]
+ coefs = coefs[ which(coefs[,'direction'] %in% direction), ]
#
- vars = unique( c(coefs[,'first'],coefs[,'second']) )
+ #vars = unique( c(coefs[,'first'],coefs[,'second']) )
+ vars = colnames(fit$tmb_inputs$data$y_tj)
out = list( "coef"=array(0, dim=rep(length(vars),2), dimnames=list(vars,vars)) )
out$coef[as.matrix(coefs[,c('first','second')])] = coefs[,what]
class(out) = "fitted_DAG"
return(out)
}
+
+#' @title Convert dsem to sem output
+#'
+#' @description Convert output from package dsem to sem
+#'
+#' @param object Output from \code{\link{dsem}}
+#' @param lag what lag to extract and visualize
+#'
+#' @return Convert output to format supplied by \code{\link[sem]{sem}}
+#'
+#' @export
+as_sem <-
+function( object,
+ lag = 0 ){
+
+ Rho = t(as_fitted_DAG( object, what="Estimate", direction=1, lag=lag )$coef)
+ Gamma = as_fitted_DAG( object, what="Estimate", direction=2, lag=lag )$coef
+ Gammainv = diag(1/diag(Gamma))
+ Linv = Gammainv %*% (diag(nrow(Rho))-Rho)
+ Sinv = t(Linv) %*% Linv
+ Sprime = solve(Sinv)
+ Sprime = 0.5*Sprime + 0.5*t(Sprime)
+
+ model = object$sem_full
+ model = model[model[,2]==0,c(1,3,4)]
+ out = sem( model,
+ S = Sprime,
+ N = nrow(eval(object$call$tsdata)) )
+
+ # pass out
+ return(out)
+
+ #x = rnorm(10)
+ #y = x + rnorm(10)
+ #object = dsem( sem="x->y, 0, beta", tsdata=ts(cbind(x,y)) )
+ #mysem = as_sem(object)
+ #myplot = semPlot::semPlotModel( mysem )
+ #semPlot::semPaths( myplot,
+ # whatLabels = "est",
+ # edge.label.cex = 1.5,
+ # node.width = 4,
+ # node.height = 2,
+ # shapeMan = "rectangle",
+ # edge.width = 4,
+ # nodeLabels = myplot@Vars$name,
+ # nDigits=4 )
+}
+
+
diff --git a/R/make_dsem_ram.R b/R/make_dsem_ram.R
new file mode 100644
index 0000000..ee05363
--- /dev/null
+++ b/R/make_dsem_ram.R
@@ -0,0 +1,362 @@
+#' @title Make a RAM (Reticular Action Model)
+#'
+#' @description \code{make_dsem_ram} converts SEM arrow notation to \code{ram} describing SEM parameters
+#'
+#' @inheritParams dsem
+#' @param times A character vector listing the set of times in order
+#' @param variables A character vector listing the set of variables
+#' @param quiet Boolean indicating whether to print messages to terminal
+#' @param remove_na Boolean indicating whether to remove NA values from RAM (default) or not.
+#' \code{remove_NA=FALSE} might be useful for exploration and diagnostics for
+#' advanced users
+#'
+#' @details
+#' \strong{RAM specification using arrow-and-lag notation}
+#'
+#' Each line of the RAM specification for \code{\link[dsem]{make_dsem_ram}} consists of four (unquoted) entries,
+#' separated by commas:
+#'
+#' \describe{
+#' \item{1. Arrow specification:}{This is a simple formula, of the form
+#' \code{A -> B} or, equivalently, \code{B <- A} for a regression
+#' coefficient (i.e., a single-headed or directional arrow);
+#' \code{A <-> A} for a variance or \code{A <-> B} for a covariance
+#' (i.e., a double-headed or bidirectional arrow). Here, \code{A} and
+#' \code{B} are variable names in the model. If a name does not correspond
+#' to an observed variable, then it is assumed to be a latent variable.
+#' Spaces can appear freely in an arrow specification, and
+#' there can be any number of hyphens in the arrows, including zero: Thus,
+#' e.g., \code{A->B}, \code{A --> B}, and \code{A>B} are all legitimate
+#' and equivalent.}
+#' \item{2. Lag (using positive values):}{An integer specifying whether the linkage
+#' is simultaneous (\code{lag=0}) or lagged (e.g., \code{X -> Y, 1, XtoY}
+#' indicates that X in time T affects Y in time T+1), where
+#' only one-headed arrows can be lagged. Using positive values to indicate lags
+#' then matches the notational convention used in package \pkg{dynlm}.}
+#' \item{3. Parameter name:}{The name of the regression coefficient, variance,
+#' or covariance specified by the arrow. Assigning the same name to two or
+#' more arrows results in an equality constraint. Specifying the parameter name
+#' as \code{NA} produces a fixed parameter.}
+#' \item{4. Value:}{start value for a free parameter or value of a fixed parameter.
+#' If given as \code{NA} (or simply omitted), the model is provide a default
+#' starting value.}
+#' }
+#'
+#' Lines may end in a comment following #. The function extends code copied from package
+#' `sem` under licence GPL (>= 2) with permission from John Fox.
+#'
+#' \strong{Simultaneous autoregressive process for simultaneous and lagged effects}
+#'
+#' This text then specifies linkages in a multivariate time-series model for variables \eqn{\mathbf X}
+#' with dimensions \eqn{T \times C} for \eqn{T} times and \eqn{C} variables.
+#' \code{make_dsem_ram} then parses this text to build a path matrix \eqn{\mathbf{P}} with
+#' dimensions \eqn{TC \times TC}, where element \eqn{\rho_{k_2,k_1}}
+#' represents the impact of \eqn{x_{t_1,c_1}} on \eqn{x_{t_2,c_2}}, where \eqn{k_1=T c_1+t_1}
+#' and \eqn{k_2=T c_2+t_2}. This path matrix defines a simultaneous equation
+#'
+#' \deqn{ \mathrm{vec}(\mathbf X) = \mathbf P \mathrm{vec}(\mathbf X) + \mathrm{vec}(\mathbf \Delta)}
+#'
+#' where \eqn{\mathbf \Delta} is a matrix of exogenous errors with covariance \eqn{\mathbf{V = \Gamma \Gamma}^t},
+#' where \eqn{\mathbf \Gamma} is the Cholesky of exogenous covariance. This
+#' simultaneous autoregressive (SAR) process then results in \eqn{\mathbf X} having covariance:
+#'
+#' \deqn{ \mathrm{Cov}(\mathbf X) = \mathbf{(I - P)}^{-1} \mathbf{\Gamma \Gamma}^t \mathbf{((I - P)}^{-1})^t }
+#'
+#' Usefully, computing the inverse-covariance (precision) matrix \eqn{\mathbf{Q = V}^{-1}} does not require inverting \eqn{\mathbf{(I - P)}}:
+#'
+#' \deqn{ \mathbf{Q} = (\mathbf{\Gamma}^{-1} \mathbf{(I - P)})^t \mathbf{\Gamma}^{-1} \mathbf{(I - P)} }
+#'
+#' \strong{Example: univariate first-order autoregressive model}
+#'
+#' This simultaneous autoregressive (SAR) process across variables and times
+#' allows the user to specify both simutanous effects (effects among variables within
+#' year \eqn{T}) and lagged effects (effects among variables among years \eqn{T}).
+#' As one example, consider a univariate and first-order autoregressive process where \eqn{T=4}.
+#' with independent errors. This is specified by passing \code{ sem = "X -> X, 1, rho \n X <-> X, 0, sigma" } to \code{make_dsem_ram}.
+#' This is then parsed to a RAM:
+#'
+#' \tabular{rrrrr}{
+#' \strong{heads} \tab \strong{to} \tab \strong{from} \tab \strong{paarameter} \tab \strong{start} \cr
+#' 1 \tab 2 \tab 1 \tab 1 \tab \cr
+#' 1 \tab 3 \tab 2 \tab 1 \tab \cr
+#' 1 \tab 4 \tab 3 \tab 1 \tab \cr
+#' 2 \tab 1 \tab 1 \tab 2 \tab \cr
+#' 2 \tab 2 \tab 2 \tab 2 \tab \cr
+#' 2 \tab 3 \tab 3 \tab 2 \tab \cr
+#' 2 \tab 4 \tab 4 \tab 2 \tab
+#' }
+#'
+#' Rows of this RAM where \code{heads=1} are then interpreted to construct the path matrix \eqn{\mathbf P}, where column "from"
+#' in the RAM indicates column number in the matrix, column "to" in the RAM indicates row number in the matrix:
+#'
+#' \deqn{ \mathbf P = \begin{bmatrix}
+#' 0 & 0 & 0 & 0 \\
+#' \rho & 0 & 0 & 0 \\
+#' 0 & \rho & 0 & 0 \\
+#' 0 & 0 & \rho & 0\\
+#' \end{bmatrix} }
+#'
+#' While rows where \code{heads=2} are interpreted to construct the Cholesky of exogenous covariance \eqn{\mathbf \Gamma}
+#' and column "parameter" in the RAM associates each nonzero element of those
+#' two matrices with an element of a vector of estimated parameters:
+#'
+#' \deqn{ \mathbf \Gamma = \begin{bmatrix}
+#' \sigma & 0 & 0 & 0 \\
+#' 0 & \sigma & 0 & 0 \\
+#' 0 & 0 & \sigma & 0 \\
+#' 0 & 0 & 0 & \sigma\\
+#' \end{bmatrix} }
+#'
+#' with two estimated parameters \eqn{\mathbf \beta = (\rho, \sigma) }. This then results in covariance:
+#'
+#' \deqn{ \mathrm{Cov}(\mathbf X) = \sigma^2 \begin{bmatrix}
+#' 1 & \rho^1 & \rho^2 & \rho^3 \\
+#' \rho^1 & 1 + \rho^2 & \rho^1 (1 + \rho^2) & \rho^2 (1 + \rho^2) \\
+#' \rho^2 & \rho^1 (1 + \rho^2) & 1 + \rho^2 + \rho^4 & \rho^1 (1 + \rho^2 + \rho^4) \\
+#' \rho^3 & \rho^2 (1 + \rho^2) & \rho^1 (1 + \rho^2 + \rho^4) & 1 + \rho^2 + \rho^4 + \rho^6 \\
+#' \end{bmatrix} }
+#'
+#' Which converges on the stationary covariance for an AR1 process for times \eqn{t>>1}:
+#'
+#' \deqn{ \mathrm{Cov}(\mathbf X) = \frac{\sigma^2}{1+\rho^2} \begin{bmatrix}
+#' 1 & \rho^1 & \rho^2 & \rho^3 \\
+#' \rho^1 & 1 & \rho^1 & \rho^2 \\
+#' \rho^2 & \rho^1 & 1 & \rho^1 \\
+#' \rho^3 & \rho^2 & \rho^1 & 1\\
+#' \end{bmatrix} }
+#'
+#' except having a lower pointwise variance for the initial times, which arises as a "boundary effect".
+#'
+#' Similarly, the arrow-and-lag notation can be used to specify a SAR representing
+#' a conventional structural equation model (SEM), cross-lagged (a.k.a. vector autoregressive)
+#' models (VAR), dynamic factor analysis (DFA), or many other time-series models.
+#'
+#' @return A reticular action module (RAM) describing dependencies
+#'
+#' @examples
+#' # Univariate AR1
+#' sem = "
+#' X -> X, 1, rho
+#' X <-> X, 0, sigma
+#' "
+#' make_dsem_ram( sem=sem, variables="X", times=1:4 )
+#'
+#' # Univariate AR2
+#' sem = "
+#' X -> X, 1, rho1
+#' X -> X, 2, rho2
+#' X <-> X, 0, sigma
+#' "
+#' make_dsem_ram( sem=sem, variables="X", times=1:4 )
+#'
+#' # Bivariate VAR
+#' sem = "
+#' X -> X, 1, XtoX
+#' X -> Y, 1, XtoY
+#' Y -> X, 1, YtoX
+#' Y -> Y, 1, YtoY
+#' X <-> X, 0, sdX
+#' Y <-> Y, 0, sdY
+#' "
+#' make_dsem_ram( sem=sem, variables=c("X","Y"), times=1:4 )
+#'
+#' # Dynamic factor analysis with one factor and two manifest variables
+#' # (specifies a random-walk for the factor, and miniscule residual SD)
+#' sem = "
+#' factor -> X, 0, loadings1
+#' factor -> Y, 0, loadings2
+#' factor -> factor, 1, NA, 1
+#' X <-> X, 0, NA, 0.01 # Fix at negligible value
+#' Y <-> Y, 0, NA, 0.01 # Fix at negligible value
+#' "
+#' make_dsem_ram( sem=sem, variables=c("X","Y","factor"), times=1:4 )
+#'
+#' # ARIMA(1,1,0)
+#' sem = "
+#' factor -> factor, 1, rho1 # AR1 component
+#' X -> X, 1, NA, 1 # Integrated component
+#' factor -> X, 0, NA, 1
+#' X <-> X, 0, NA, 0.01 # Fix at negligible value
+#' "
+#' make_dsem_ram( sem=sem, variables=c("X","factor"), times=1:4 )
+#'
+#' # ARIMA(0,0,1)
+#' sem = "
+#' factor -> X, 0, NA, 1
+#' factor -> X, 1, rho1 # MA1 component
+#' X <-> X, 0, NA, 0.01 # Fix at negligible value
+#' "
+#' make_dsem_ram( sem=sem, variables=c("X","factor"), times=1:4 )
+#'
+#' @export
+make_dsem_ram <-
+function( sem,
+ times,
+ variables,
+ quiet = FALSE,
+ remove_na = TRUE ){
+ # Docs : https://roxygen2.r-lib.org/articles/formatting.html
+
+ # MATH CHECK IN ROXYGEN DOCS ABOVE
+ if( FALSE ){
+ rho = 0.8
+ sigma = 0.5
+ Rho = Gamma = matrix(0, nrow=4, ncol=4)
+ Rho[cbind(2:4,1:3)] = rho
+ Gamma = I = diag(4)
+ diag(Gamma)[] = sigma
+ # DSEM covariance
+ solve(I-Rho) %*% Gamma %*% t(Gamma) %*% t(solve(I-Rho))
+ # Stated covariance
+ sigma^2 * rbind(
+ c(1, rho, rho^2, rho^3),
+ c(rho, 1+rho^2, rho*(1+rho^2), rho^2*(1+rho^2) ),
+ c(rho^2, rho*(1+rho^2), 1+rho^2+rho^4, rho*(1+rho^2+rho^4) ),
+ c(rho^3, rho^2*(1+rho^2), rho*(1+rho^2+rho^4), 1+rho^2+rho^4+rho^6 )
+ )
+ }
+
+ ####### Error checks
+ if( !is.numeric(times) ) stop("`times` must be numeric in `make_dsem_ram`")
+
+ ####### Define local functions
+ # helper function
+ match_row = function( df, x ) which( df[1]==x[1] & df[2]==x[2] )
+ #
+ add.variances <- function() {
+ variables <- need.variance()
+ nvars <- length(variables)
+ if (nvars == 0)
+ return(model)
+ message("NOTE: adding ", nvars, " variances to the model")
+ paths <- character(nvars)
+ par.names <- character(nvars)
+ for (i in 1:nvars) {
+ paths[i] <- paste(variables[i], "<->", variables[i])
+ par.names[i] <- paste("V[", variables[i], "]", sep = "")
+ }
+ model.2 <- cbind(
+ 'path' = c(model[, 1], paths),
+ 'lag' = c(model[,2], rep(0,nvars)),
+ 'name' = c(model[, 3], par.names),
+ 'start' = c(model[, 4], rep(NA, length(paths))) )
+ model.2
+ }
+ need.variance <- function() {
+ all.vars <- classify_variables(model)
+ exo.vars <- all.vars$exogenous
+ end.vars <- all.vars$endogenous
+ variables <- logical(0)
+ for (i in seq_len(nrow(model))) {
+ paths = model[i,1]
+ lag = model[i,2]
+ vars <- gsub(pattern=" ", replacement="", x=paths)
+ vars <- sub("-*>", "->", sub("<-*", "<-", vars))
+ vars <- sub("<->|<-", "->", vars)
+ vars <- strsplit(vars, "->")[[1]]
+ if ((vars[1] != vars[2]) | (lag != 0)) {
+ for (a.variable in vars) {
+ if (is.na(variables[a.variable]))
+ variables[a.variable] <- TRUE
+ }
+ }
+ else {
+ variables[vars[1]] <- FALSE
+ }
+ }
+ if (!exog.variances && length(exo.vars) > 0)
+ variables[exo.vars] <- FALSE
+ if (!endog.variances && length(end.vars) > 0)
+ variables[end.vars] <- FALSE
+ names(variables)[variables]
+ }
+
+ ####### Step 2 -- Make RAM
+ # convert to data frame
+ model = scan( text = sem,
+ what = list(path = "", lag = 1, par = "", start = 1, dump = ""),
+ sep = ",",
+ strip.white = TRUE,
+ comment.char = "#",
+ fill = TRUE,
+ quiet = quiet)
+ model$path <- gsub("\\t", " ", model$path)
+ model$par[model$par == ""] <- NA
+ model <- cbind( "path"=model$path, "lag"=model$lag, "name"=model$par, "start"=model$start)
+
+ #if( !is.null(covs) ){
+ # for (cov in covs) {
+ # vars <- strsplit(cov, "[ ,]+")[[1]]
+ # nvar <- length(vars)
+ # for (i in 1:nvar) {
+ # for (j in i:nvar) {
+ # p1 = paste(vars[i], "<->", vars[j])
+ # p2 = if (i==j) paste("V[", vars[i], "]", sep = "") else paste("C[",vars[i], ",", vars[j], "]", sep = "")
+ # p3 = NA
+ # row <- c(p1, 0, p2, p3)
+ # if( any((row[1]==model[,1]) & (row[2]==model[,2])) ){
+ # next
+ # }else{
+ # model <- rbind(model, row, deparse.level = 0)
+ # }
+ # }}
+ # }
+ #}
+
+ exog.variances = endog.variances = TRUE
+ model = add.variances()
+
+ ####### Step 2 -- Make RAM
+
+ # Global stuff
+ Q_names = expand.grid( times, variables )
+ ram = NULL # heads, to, from, parameter
+
+ # Deal with fixed values
+ par.names = model[, 3]
+ pars = na.omit(unique(par.names))
+ par.nos = apply(outer(pars, par.names, "=="), 2, which)
+ #par.nos = ifelse( sapply(par.nos,length)==0, 0, unlist(par.nos) )
+ par.nos = unlist(sapply( par.nos, FUN=\(x) ifelse(length(x)==0, 0, x) ))
+ model = cbind( model, "parameter"=par.nos )
+ startvalues = model[,4]
+
+ # Add incidence to model
+ model = cbind( model, first=NA, second=NA, direction=NA )
+ for( i in seq_len(nrow(model)) ){
+ path = parse_path(model[i,1])
+ model[i,c('first','second','direction')] = unlist( path[c('first','second','direction')] )
+ }
+
+ # Loop through paths
+ for( i in seq_len(nrow(model)) ){
+ for( t in seq_along(times) ){
+ lag = as.numeric(model[i,2])
+ par.no = par.nos[i]
+ # Get index for "from"
+ from = c( times[t], model[i,'first'] )
+ from_index = match_row( Q_names, from )
+ from_index = ifelse( length(from_index)==0, NA, from_index )
+ # Get index for "to"
+ to = c( times[t+lag], model[i,'second'] )
+ to_index = match_row( Q_names, to )
+ to_index = ifelse( length(to_index)==0, NA, to_index )
+ ram_new = data.frame( "heads"=abs(as.numeric(model[i,'direction'])), "to"=to_index, "from"=from_index, "parameter"=par.no, "start"=startvalues[i] )
+ ram = rbind( ram, ram_new )
+ }}
+ rownames(ram) = NULL
+
+ #
+ if( isTRUE(remove_na) ){
+ which_keep = which(apply( ram[,1:4], MARGIN=1, FUN=\(x)!any(is.na(x)) ))
+ ram = ram[ which_keep, ]
+ }
+
+ #
+ out = list( "model"=model,
+ "ram"=ram,
+ "variables" = variables,
+ "times" = times )
+ class(out) = "dsem_ram"
+ return(out)
+}
diff --git a/R/make_ram.R b/R/make_ram.R
deleted file mode 100644
index 7c3a131..0000000
--- a/R/make_ram.R
+++ /dev/null
@@ -1,159 +0,0 @@
-#' Make a RAM (Reticular Action Model)
-#'
-#' \code{make_ram} converts SEM arrow notation to \code{ram} describing SEM parameters
-#'
-#' @inheritParams dsem
-#' @param remove_na Boolean indicating whether to remove NA values from RAM (default) or not.
-#' \code{remove_NA=FALSE} might be useful for exploration and diagnostics for
-#' advanced users
-#'
-#' Copied and then modified with permission from John Fox under licence GPL (>= 2)
-#'
-#' @return the standard output from \code{\link[stats]{nlminb}}, except with additional diagnostics and timing info,
-#' and a new slot containing the output from \code{\link[TMB]{sdreport}}
-#'
-#' @export
-make_ram <-
-function( sem,
- tsdata,
- covs = NULL,
- quiet = FALSE,
- remove_na = TRUE ){
-
- ####### Define location functions
- # helper function
- match_row = function( df, x ) which( df[1]==x[1] & df[2]==x[2] )
- #
- add.variances <- function() {
- variables <- need.variance()
- nvars <- length(variables)
- if (nvars == 0)
- return(model)
- message("NOTE: adding ", nvars, " variances to the model")
- paths <- character(nvars)
- par.names <- character(nvars)
- for (i in 1:nvars) {
- paths[i] <- paste(variables[i], "<->", variables[i])
- par.names[i] <- paste("V[", variables[i], "]", sep = "")
- }
- model.2 <- cbind(c(model[, 1], paths), c(model[,2], rep(0,nvars)), c(model[, 3],
- par.names), c(model[, 4], rep(NA, length(paths))))
- model.2
- }
- need.variance <- function() {
- all.vars <- classify_variables(model)
- exo.vars <- all.vars$exogenous
- end.vars <- all.vars$endogenous
- variables <- logical(0)
- for (i in seq_len(nrow(model))) {
- paths = model[i,1]
- lag = model[i,2]
- vars <- gsub(pattern=" ", replacement="", x=paths)
- vars <- sub("-*>", "->", sub("<-*", "<-", vars))
- vars <- sub("<->|<-", "->", vars)
- vars <- strsplit(vars, "->")[[1]]
- if ((vars[1] != vars[2]) | (lag != 0)) {
- for (a.variable in vars) {
- if (is.na(variables[a.variable]))
- variables[a.variable] <- TRUE
- }
- }
- else {
- variables[vars[1]] <- FALSE
- }
- }
- if (!exog.variances && length(exo.vars) > 0)
- variables[exo.vars] <- FALSE
- if (!endog.variances && length(end.vars) > 0)
- variables[end.vars] <- FALSE
- names(variables)[variables]
- }
-
- ####### Step 2 -- Make RAM
- # convert to data frame
- model = scan( text = sem,
- what = list(path = "", lag = 1, par = "", start = 1, dump = ""),
- sep = ",",
- strip.white = TRUE,
- comment.char = "#",
- fill = TRUE,
- quiet = quiet)
- model$path <- gsub("\\t", " ", model$path)
- model$par[model$par == ""] <- NA
- model <- cbind( model$path, model$lag, model$par, model$start)
-
- if( !is.null(covs) ){
- for (cov in covs) {
- vars <- strsplit(cov, "[ ,]+")[[1]]
- nvar <- length(vars)
- for (i in 1:nvar) {
- for (j in i:nvar) {
- p1 = paste(vars[i], "<->", vars[j])
- p2 = if (i==j) paste("V[", vars[i], "]", sep = "") else paste("C[",vars[i], ",", vars[j], "]", sep = "")
- p3 = NA
- row <- c(p1, 0, p2, p3)
- if( any((row[1]==model[,1]) & (row[2]==model[,2])) ){
- next
- }else{
- model <- rbind(model, row, deparse.level = 0)
- }
- }}
- }
- }
-
- exog.variances = endog.variances = TRUE
- model = add.variances()
-
- ####### Step 2 -- Make RAM
-
- # Global stuff
- Q_dimnames = dimnames(.preformat.ts(tsdata))
- if(any(sapply(Q_dimnames,is.null))) stop("Check dimnames")
- Q_names = expand.grid(Q_dimnames)
- ram = NULL # heads, to, from, parameter
- vars = Q_dimnames[[2]]
-
- # Deal with fixed values
- par.names = model[, 3]
- pars = na.omit(unique(par.names))
- par.nos = apply(outer(pars, par.names, "=="), 2, which)
- #par.nos = ifelse( sapply(par.nos,length)==0, 0, unlist(par.nos) )
- par.nos = unlist(sapply( par.nos, FUN=\(x) ifelse(length(x)==0, 0, x) ))
- model = cbind( model, "parameter"=par.nos )
- startvalues = model[,4]
-
- # Add incidence to model
- model = cbind( model, first=NA, second=NA, direction=NA )
- for( i in seq_len(nrow(model)) ){
- path = parse_path(model[i,1])
- model[i,c('first','second','direction')] = unlist( path[c('first','second','direction')] )
- }
-
- # Loop through paths
- for( i in seq_len(nrow(model)) ){
- for( t in 1:nrow(tsdata) ){
- lag = as.numeric(model[i,2])
- par.no = par.nos[i]
- # Get index for "from"
- from = c( Q_dimnames[[1]][t], model[i,'first'] )
- from_index = match_row( Q_names, from )
- from_index = ifelse( length(from_index)==0, NA, from_index )
- # Get index for "to"
- to = c( Q_dimnames[[1]][t-lag], model[i,'second'] )
- to_index = match_row( Q_names, to )
- to_index = ifelse( length(to_index)==0, NA, to_index )
- ram_new = data.frame( "heads"=abs(as.numeric(model[i,'direction'])), "to"=to_index, "from"=from_index, "parameter"=par.no, "start"=startvalues[i] )
- ram = rbind( ram, ram_new )
- }}
- rownames(ram) = NULL
-
- #
- if( isTRUE(remove_na) ){
- which_keep = which(apply( ram[,1:4], MARGIN=1, FUN=\(x)!any(is.na(x)) ))
- ram = ram[ which_keep, ]
- }
-
- #
- out = list( "model"=model, "ram"=ram)
- return(out)
-}
diff --git a/R/parse_path.R b/R/parse_path.R
index 0d9179a..8d685a0 100644
--- a/R/parse_path.R
+++ b/R/parse_path.R
@@ -1,13 +1,15 @@
-#' Parse path
+#' @title Parse path
#'
-#' \code{parse_path} is copied from \code{sem::parse.path}
+#' @description \code{parse_path} is copied from \code{sem::parse.path}
#'
-#' Copied with permission from John Fox under licence GPL (>= 2)
+#' @details
+#' Copied from package `sem` under licence GPL (>= 2) with permission from John Fox
#'
#' @return Tagged-list defining variables and direction for a specified path coefficient
#'
#' @param path text to parse
+#' @export
parse_path <-
function( path ){
path.1 <- gsub("-", "", gsub(" ", "", path))
@@ -24,3 +26,4 @@ function( path ){
out = list(first = path.1[1], second = path.1[length(path.1)], direction = direction)
return(out)
}
+
diff --git a/inst/tmbstan/summary_mcmc.RDS b/inst/tmbstan/summary_mcmc.RDS
new file mode 100644
index 0000000..48e43f4
Binary files /dev/null and b/inst/tmbstan/summary_mcmc.RDS differ
diff --git a/man/as_fitted_DAG.Rd b/man/as_fitted_DAG.Rd
index fdbe23e..a542b44 100644
--- a/man/as_fitted_DAG.Rd
+++ b/man/as_fitted_DAG.Rd
@@ -4,7 +4,7 @@
\alias{as_fitted_DAG}
\title{Convert output from package dsem to phylopath}
\usage{
-as_fitted_DAG(fit, lag = 0, what = "Estimate")
+as_fitted_DAG(fit, lag = 0, what = "Estimate", direction = 1)
}
\arguments{
\item{fit}{Output from \code{\link{dsem}}}
@@ -13,6 +13,8 @@ as_fitted_DAG(fit, lag = 0, what = "Estimate")
\item{what}{whether to output estimates \code{what="Estimate"}, standard errors \code{what="Std_Error"}
or p-values \code{what="Std_Error"}}
+
+\item{direction}{whether to include one-sided arrows \code{direction=1}, or both one- and two-sided arrows \code{direction=c(1,2)}}
}
\value{
Convert output to format supplied by \code{\link[phylopath]{est_DAG}}
diff --git a/man/as_sem.Rd b/man/as_sem.Rd
new file mode 100644
index 0000000..4a0d6a0
--- /dev/null
+++ b/man/as_sem.Rd
@@ -0,0 +1,19 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/dsem.R
+\name{as_sem}
+\alias{as_sem}
+\title{Convert dsem to sem output}
+\usage{
+as_sem(object, lag = 0)
+}
+\arguments{
+\item{object}{Output from \code{\link{dsem}}}
+
+\item{lag}{what lag to extract and visualize}
+}
+\value{
+Convert output to format supplied by \code{\link[sem]{sem}}
+}
+\description{
+Convert output from package dsem to sem
+}
diff --git a/man/classify_variables.Rd b/man/classify_variables.Rd
index fb64a08..bf5fac6 100644
--- a/man/classify_variables.Rd
+++ b/man/classify_variables.Rd
@@ -16,5 +16,5 @@ Tagged-list defining exogenous and endogenous variables
\code{classify_variables} is copied from \code{sem:::classifyVariables}
}
\details{
-Copied with permission from John Fox under licence GPL (>= 2)
+Copied from package `sem` under licence GPL (>= 2) with permission from John Fox
}
diff --git a/man/dsem.Rd b/man/dsem.Rd
index 7874d1f..2eeefb6 100644
--- a/man/dsem.Rd
+++ b/man/dsem.Rd
@@ -8,20 +8,15 @@ dsem(
sem,
tsdata,
family = rep("fixed", ncol(tsdata)),
- covs = colnames(tsdata),
estimate_delta0 = FALSE,
- quiet = FALSE,
- run_model = TRUE,
- use_REML = TRUE,
- parameters = NULL,
- map = NULL,
+ control = dsem_control(),
...
)
}
\arguments{
-\item{sem}{structural equation model structure, passed to either \code{\link[sem]{specifyModel}}
-or \code{\link[sem]{specifyEquations}} and then parsed to control
-the set of path coefficients and variance-covariance parameters}
+\item{sem}{Specification for time-series structural equation model structure
+including lagged or simultaneous effects. See Details section in
+\code{\link[dsem]{make_dsem_ram}} for more description}
\item{tsdata}{time-series data, as outputted using \code{\link[stats]{ts}}}
@@ -34,20 +29,8 @@ Other options correspond to different specifications of measurement error.}
as fixed effects, or alternatively to assume that dynamics start at some stochastic draw away from
the stationary distribution}
-\item{quiet}{Boolean indicating whether to run model printing messages to terminal or not;}
-
-\item{run_model}{Boolean indicating whether to estimate parameters (the default), or
-instead to return the model inputs and compiled TMB object without running;}
-
-\item{use_REML}{Boolean indicating whether to treat non-variance fixed effects as random,
-either to motigate bias in estimated variance parameters or improve efficiency for
-parameter estimation given correlated fixed and random effects}
-
-\item{parameters}{list of fixed and random effects, e.g., as constructed by \code{dsem} and then modified
-by hand (only helpful for advanced users to change starting values or restart at intended values)}
-
-\item{map}{list of fixed and mirrored parameters, constructed by \code{dsem} by default but available
-to override this default and then pass to \code{\link[TMB]{MakeADFun}}}
+\item{control}{Output from \code{\link{dsem_control}}, used to define user
+settings, and see documentation for that function for details.}
\item{...}{Additional parameters passed to \code{\link{fit_tmb}}}
}
@@ -55,8 +38,8 @@ to override this default and then pass to \code{\link[TMB]{MakeADFun}}}
An object (list) of class `dsem`. Elements include:
\describe{
\item{obj}{TMB object from \code{\link[TMB]{MakeADFun}}}
-\item{ram}{RAM parsed by \code{make_ram}}
-\item{model}{SEM model parsed from \code{sem} using \code{\link[sem]{specifyModel}} or \code{\link[sem]{specifyEquations}}}
+\item{ram}{RAM parsed by \code{make_dsem_ram}}
+\item{model}{SEM structure parsed by \code{make_dsem_ram} as intermediate description of model linkages}
\item{tmb_inputs}{The list of inputs passed to \code{\link[TMB]{MakeADFun}}}
\item{opt}{The output from \code{\link{fit_tmb}}}
}
@@ -64,65 +47,67 @@ An object (list) of class `dsem`. Elements include:
\description{
Fits a dynamic structural equation model
}
+\details{
+A DSEM involves (at a minimum):
+\describe{
+ \item{Time series}{a matrix \eqn{\mathbf X} where column \eqn{\mathbf x_c} for variable c is
+ a time-series;}
+ \item{Path diagram}{a user-supplied specification for the path coefficients, which
+ define the precision (inverse covariance) \eqn{\mathbf Q} for a matrix of state-variables
+ and see \code{\link{make_dsem_ram}} for more details on the math involved.}
+}
+The model also estimates the time-series mean \eqn{ \mathbf{\mu}_c } for each variable.
+The mean and precision matrix therefore define a Gaussian Markov random field for \eqn{\mathbf X}:
+
+\deqn{ \mathrm{vec}(\mathbf X) \sim \mathrm{MVN}( \mathrm{vec}(\mathbf{I_T} \otimes \mathbf{\mu}), \mathbf{Q}^{-1}) }
+
+Users can the specify
+a distribution for measurement errors (or assume that variables are measured without error) using
+argument \code{family}. This defines the link-function \eqn{g_c(.)} and distribution \eqn{f_c(.)}
+for each time-series \eqn{c}:
+
+\deqn{ y_{t,c} \sim f_c( g_c^{-1}( x_{t,c} ), \theta_c )}
+
+\code{dsem} then estimates all specified coefficients, time-series means \eqn{\mu_c}, and distribution
+measurement errors \eqn{\theta_c} via maximizing a log-marginal likelihood, while
+also estimating state-variables \eqn{x_{t,c}}.
+\code{summary.dsem} then assembles estimates and standard errors in an easy-to-read format.
+Standard errors for fixed effects (path coefficients, exogenoux variance parameters, and measurement error parameters)
+are estimated from the matrix of second derivatives of the log-marginal likelihod,
+and standard errors for random effects (i.e., missing or state-space variables) are estimated
+from a generalization of this method (see \code{\link[TMB]{sdreport}} for details).
+}
\examples{
# Define model
sem = "
- Profits -> Consumption, 0, a2
- Profits -> Consumption, -1, a3
- Priv_wage -> Consumption, 0, a4
- Gov_wage -> Consumption, 0, a4
- Consumption <-> Consumption, 0, v1
- Consumption -> Consumption, -1, ar1
- Consumption -> Consumption, -2, ar2
- Profits -> Investment, 0, b2
- Profits -> Investment, -1, b3
- Capital_stock -> Investment, -1, b4
- Investment <-> Investment, 0, v2
- neg_Gov_wage <-> neg_Gov_wage, 0, v3
- GNP -> Priv_wage, 0, c2
- Taxes -> Priv_wage, 0, c2
- neg_Gov_wage -> Priv_wage, 0, c2
- GNP -> Priv_wage, -1, c3
- Taxes -> Priv_wage, -1, c3
- neg_Gov_wage -> Priv_wage, -1, c3
- Time -> Priv_wage, 0, c4
- Priv_wage <-> Priv_wage, 0, v4
- GNP <-> GNP, 0, v5
- Profits <-> Profits, 0, v6
- Capital_stock <-> Capital_stock, 0, v7
- Taxes <-> Taxes, 0, v8
- Time <-> Time, 0, v9
- Gov_wage <-> Gov_wage, 0, v10
- Gov_expense <-> Gov_expense, 0, v11
+ # Link, lag, param_name
+ cprofits -> consumption, 0, a1
+ cprofits -> consumption, 1, a2
+ pwage -> consumption, 0, a3
+ gwage -> consumption, 0, a3
+ cprofits -> invest, 0, b1
+ cprofits -> invest, 1, b2
+ capital -> invest, 0, b3
+ gnp -> pwage, 0, c2
+ gnp -> pwage, 1, c3
+ time -> pwage, 0, c1
"
# Load data
data(KleinI, package="AER")
-Data = as.data.frame(KleinI)
-Data = cbind( Data, "time" = seq(1,22)-11 )
-colnames(Data) = sapply( colnames(Data), FUN=switch,
- "consumption"="Consumption", "invest"="Investment",
- "cprofits"="Profits", "capital"="Capital_stock", "gwage"="Gov_wage",
- "pwage"="Priv_wage", "gexpenditure"="Gov_expense", "taxes"="Taxes",
- "time"="Time", "gnp"="GNP")
-Z = ts( cbind(Data, "neg_Gov_wage"=-1*Data[,'Gov_wage']) )
+TS = ts(data.frame(KleinI, "time"=time(KleinI) - 1931))
+tsdata = TS[,c("time","gnp","pwage","cprofits",'consumption',
+ "gwage","invest","capital")]
# Fit model
-fit = dsem( sem=sem, tsdata=Z )
+fit = dsem( sem=sem,
+ tsdata = tsdata,
+ newtonsteps = 0,
+ estimate_delta0 = TRUE,
+ control = dsem_control(quiet=TRUE) )
summary( fit )
-
-# Plot results
-library(ggplot2)
-library(ggpubr)
-library(phylopath)
-p1 = plot(as_fitted_DAG(fit), text_size=3, type="width", show.legend=FALSE)
-p1$layers[[1]]$mapping$edge_width = 0.5
-p2 = plot(as_fitted_DAG(fit, lag=-1), text_size=3, type="width", show.legend=FALSE)
-p2$layers[[1]]$mapping$edge_width = 0.25
-ggarrange(p1 + scale_x_continuous(expand = c(0.2, 0.0)),
- p2 + scale_x_continuous(expand = c(0.2, 0.0)),
- labels = c("Simultaneous effects", "Lag-1 effects"),
- ncol = 1, nrow = 2)
+plot( fit )
+plot( fit, edge_label="value" )
}
\references{
diff --git a/man/dsem_control.Rd b/man/dsem_control.Rd
new file mode 100644
index 0000000..46c583c
--- /dev/null
+++ b/man/dsem_control.Rd
@@ -0,0 +1,39 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/dsem.R
+\name{dsem_control}
+\alias{dsem_control}
+\title{Detailed control for dsem structure}
+\usage{
+dsem_control(
+ quiet = FALSE,
+ run_model = TRUE,
+ use_REML = TRUE,
+ parameters = NULL,
+ map = NULL
+)
+}
+\arguments{
+\item{quiet}{Boolean indicating whether to run model printing messages to terminal or not;}
+
+\item{run_model}{Boolean indicating whether to estimate parameters (the default), or
+instead to return the model inputs and compiled TMB object without running;}
+
+\item{use_REML}{Boolean indicating whether to treat non-variance fixed effects as random,
+either to motigate bias in estimated variance parameters or improve efficiency for
+parameter estimation given correlated fixed and random effects}
+
+\item{parameters}{list of fixed and random effects, e.g., as constructed by \code{dsem} and then modified
+by hand (only helpful for advanced users to change starting values or restart at intended values)}
+
+\item{map}{list of fixed and mirrored parameters, constructed by \code{dsem} by default but available
+to override this default and then pass to \code{\link[TMB]{MakeADFun}}}
+}
+\value{
+An S3 object of class "dsem_control" that specifies detailed model settings,
+allowing user specification while also specifying default values
+}
+\description{
+Define a list of control parameters. Note that
+the format of this input is likely to change more rapidly than that of
+\code{\link{dsem}}
+}
diff --git a/man/isle_royale.Rd b/man/isle_royale.Rd
index 013b0f3..963ea5a 100644
--- a/man/isle_royale.Rd
+++ b/man/isle_royale.Rd
@@ -10,4 +10,13 @@ data(isle_royale)
\description{
Data used to demonstrate and test cross-lagged (vector autoregressive) models
}
+\details{
+Data extracted from file "Data_wolves_moose_Isle_Royale_June2019.csv" available at
+\url{https://isleroyalewolf.org/data/data/home.html} and obtained 2023-06-23.
+Reproduced with permission from John Vucetich, and generated by the
+Wolves and Moose of Isle Royale project.
+}
+\references{
+Vucetich, JA and Peterson RO. 2012. The population biology of Isle Royale wolves and moose: an overview. \url{https://www.isleroyalewolf.org}
+}
\keyword{data}
diff --git a/man/logLik.dsem.Rd b/man/logLik.dsem.Rd
new file mode 100644
index 0000000..58a320c
--- /dev/null
+++ b/man/logLik.dsem.Rd
@@ -0,0 +1,26 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/dsem.R
+\name{logLik.dsem}
+\alias{logLik.dsem}
+\title{Marglinal log-likelihood}
+\usage{
+\method{logLik}{dsem}(object, ...)
+}
+\arguments{
+\item{object}{Output from \code{\link{dsem}}}
+
+\item{...}{Not used}
+}
+\value{
+object of class \code{logLik} with attributes
+ \item{val}{log-likelihood}
+ \item{df}{number of parameters}
+
+Returns an object of class logLik. This has attributes
+"df" (degrees of freedom) giving the number of (estimated) fixed effects
+in the model, abd "val" (value) giving the marginal log-likelihood.
+This class then allows \code{AIC} to work as expected.
+}
+\description{
+Extract the (marginal) log-likelihood of a dsem model
+}
diff --git a/man/make_dsem_ram.Rd b/man/make_dsem_ram.Rd
new file mode 100644
index 0000000..a279c7c
--- /dev/null
+++ b/man/make_dsem_ram.Rd
@@ -0,0 +1,206 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/make_dsem_ram.R
+\name{make_dsem_ram}
+\alias{make_dsem_ram}
+\title{Make a RAM (Reticular Action Model)}
+\usage{
+make_dsem_ram(sem, times, variables, quiet = FALSE, remove_na = TRUE)
+}
+\arguments{
+\item{sem}{Specification for time-series structural equation model structure
+including lagged or simultaneous effects. See Details section in
+\code{\link[dsem]{make_dsem_ram}} for more description}
+
+\item{times}{A character vector listing the set of times in order}
+
+\item{variables}{A character vector listing the set of variables}
+
+\item{quiet}{Boolean indicating whether to print messages to terminal}
+
+\item{remove_na}{Boolean indicating whether to remove NA values from RAM (default) or not.
+\code{remove_NA=FALSE} might be useful for exploration and diagnostics for
+advanced users}
+}
+\value{
+A reticular action module (RAM) describing dependencies
+}
+\description{
+\code{make_dsem_ram} converts SEM arrow notation to \code{ram} describing SEM parameters
+}
+\details{
+\strong{RAM specification using arrow-and-lag notation}
+
+Each line of the RAM specification for \code{\link[dsem]{make_dsem_ram}} consists of four (unquoted) entries,
+separated by commas:
+
+\describe{
+ \item{1. Arrow specification:}{This is a simple formula, of the form
+ \code{A -> B} or, equivalently, \code{B <- A} for a regression
+ coefficient (i.e., a single-headed or directional arrow);
+ \code{A <-> A} for a variance or \code{A <-> B} for a covariance
+ (i.e., a double-headed or bidirectional arrow). Here, \code{A} and
+ \code{B} are variable names in the model. If a name does not correspond
+ to an observed variable, then it is assumed to be a latent variable.
+ Spaces can appear freely in an arrow specification, and
+ there can be any number of hyphens in the arrows, including zero: Thus,
+ e.g., \code{A->B}, \code{A --> B}, and \code{A>B} are all legitimate
+ and equivalent.}
+ \item{2. Lag (using positive values):}{An integer specifying whether the linkage
+ is simultaneous (\code{lag=0}) or lagged (e.g., \code{X -> Y, 1, XtoY}
+ indicates that X in time T affects Y in time T+1), where
+ only one-headed arrows can be lagged. Using positive values to indicate lags
+ then matches the notational convention used in package \pkg{dynlm}.}
+ \item{3. Parameter name:}{The name of the regression coefficient, variance,
+ or covariance specified by the arrow. Assigning the same name to two or
+ more arrows results in an equality constraint. Specifying the parameter name
+ as \code{NA} produces a fixed parameter.}
+ \item{4. Value:}{start value for a free parameter or value of a fixed parameter.
+ If given as \code{NA} (or simply omitted), the model is provide a default
+ starting value.}
+}
+
+Lines may end in a comment following #. The function extends code copied from package
+`sem` under licence GPL (>= 2) with permission from John Fox.
+
+\strong{Simultaneous autoregressive process for simultaneous and lagged effects}
+
+This text then specifies linkages in a multivariate time-series model for variables \eqn{\mathbf X}
+with dimensions \eqn{T \times C} for \eqn{T} times and \eqn{C} variables.
+\code{make_dsem_ram} then parses this text to build a path matrix \eqn{\mathbf{P}} with
+dimensions \eqn{TC \times TC}, where element \eqn{\rho_{k_2,k_1}}
+represents the impact of \eqn{x_{t_1,c_1}} on \eqn{x_{t_2,c_2}}, where \eqn{k_1=T c_1+t_1}
+and \eqn{k_2=T c_2+t_2}. This path matrix defines a simultaneous equation
+
+\deqn{ \mathrm{vec}(\mathbf X) = \mathbf P \mathrm{vec}(\mathbf X) + \mathrm{vec}(\mathbf \Delta)}
+
+where \eqn{\mathbf \Delta} is a matrix of exogenous errors with covariance \eqn{\mathbf{V = \Gamma \Gamma}^t},
+where \eqn{\mathbf \Gamma} is the Cholesky of exogenous covariance. This
+simultaneous autoregressive (SAR) process then results in \eqn{\mathbf X} having covariance:
+
+\deqn{ \mathrm{Cov}(\mathbf X) = \mathbf{(I - P)}^{-1} \mathbf{\Gamma \Gamma}^t \mathbf{((I - P)}^{-1})^t }
+
+Usefully, computing the inverse-covariance (precision) matrix \eqn{\mathbf{Q = V}^{-1}} does not require inverting \eqn{\mathbf{(I - P)}}:
+
+\deqn{ \mathbf{Q} = (\mathbf{\Gamma}^{-1} \mathbf{(I - P)})^t \mathbf{\Gamma}^{-1} \mathbf{(I - P)} }
+
+\strong{Example: univariate first-order autoregressive model}
+
+This simultaneous autoregressive (SAR) process across variables and times
+allows the user to specify both simutanous effects (effects among variables within
+year \eqn{T}) and lagged effects (effects among variables among years \eqn{T}).
+As one example, consider a univariate and first-order autoregressive process where \eqn{T=4}.
+with independent errors. This is specified by passing \code{ sem = "X -> X, 1, rho \n X <-> X, 0, sigma" } to \code{make_dsem_ram}.
+This is then parsed to a RAM:
+
+\tabular{rrrrr}{
+ \strong{heads} \tab \strong{to} \tab \strong{from} \tab \strong{paarameter} \tab \strong{start} \cr
+ 1 \tab 2 \tab 1 \tab 1 \tab \cr
+ 1 \tab 3 \tab 2 \tab 1 \tab \cr
+ 1 \tab 4 \tab 3 \tab 1 \tab \cr
+ 2 \tab 1 \tab 1 \tab 2 \tab \cr
+ 2 \tab 2 \tab 2 \tab 2 \tab \cr
+ 2 \tab 3 \tab 3 \tab 2 \tab \cr
+ 2 \tab 4 \tab 4 \tab 2 \tab
+}
+
+Rows of this RAM where \code{heads=1} are then interpreted to construct the path matrix \eqn{\mathbf P}, where column "from"
+in the RAM indicates column number in the matrix, column "to" in the RAM indicates row number in the matrix:
+
+ \deqn{ \mathbf P = \begin{bmatrix}
+ 0 & 0 & 0 & 0 \\
+ \rho & 0 & 0 & 0 \\
+ 0 & \rho & 0 & 0 \\
+ 0 & 0 & \rho & 0\\
+ \end{bmatrix} }
+
+While rows where \code{heads=2} are interpreted to construct the Cholesky of exogenous covariance \eqn{\mathbf \Gamma}
+and column "parameter" in the RAM associates each nonzero element of those
+two matrices with an element of a vector of estimated parameters:
+
+ \deqn{ \mathbf \Gamma = \begin{bmatrix}
+ \sigma & 0 & 0 & 0 \\
+ 0 & \sigma & 0 & 0 \\
+ 0 & 0 & \sigma & 0 \\
+ 0 & 0 & 0 & \sigma\\
+ \end{bmatrix} }
+
+with two estimated parameters \eqn{\mathbf \beta = (\rho, \sigma) }. This then results in covariance:
+
+ \deqn{ \mathrm{Cov}(\mathbf X) = \sigma^2 \begin{bmatrix}
+ 1 & \rho^1 & \rho^2 & \rho^3 \\
+ \rho^1 & 1 + \rho^2 & \rho^1 (1 + \rho^2) & \rho^2 (1 + \rho^2) \\
+ \rho^2 & \rho^1 (1 + \rho^2) & 1 + \rho^2 + \rho^4 & \rho^1 (1 + \rho^2 + \rho^4) \\
+ \rho^3 & \rho^2 (1 + \rho^2) & \rho^1 (1 + \rho^2 + \rho^4) & 1 + \rho^2 + \rho^4 + \rho^6 \\
+ \end{bmatrix} }
+
+Which converges on the stationary covariance for an AR1 process for times \eqn{t>>1}:
+
+ \deqn{ \mathrm{Cov}(\mathbf X) = \frac{\sigma^2}{1+\rho^2} \begin{bmatrix}
+ 1 & \rho^1 & \rho^2 & \rho^3 \\
+ \rho^1 & 1 & \rho^1 & \rho^2 \\
+ \rho^2 & \rho^1 & 1 & \rho^1 \\
+ \rho^3 & \rho^2 & \rho^1 & 1\\
+ \end{bmatrix} }
+
+except having a lower pointwise variance for the initial times, which arises as a "boundary effect".
+
+Similarly, the arrow-and-lag notation can be used to specify a SAR representing
+a conventional structural equation model (SEM), cross-lagged (a.k.a. vector autoregressive)
+models (VAR), dynamic factor analysis (DFA), or many other time-series models.
+}
+\examples{
+# Univariate AR1
+sem = "
+ X -> X, 1, rho
+ X <-> X, 0, sigma
+"
+make_dsem_ram( sem=sem, variables="X", times=1:4 )
+
+# Univariate AR2
+sem = "
+ X -> X, 1, rho1
+ X -> X, 2, rho2
+ X <-> X, 0, sigma
+"
+make_dsem_ram( sem=sem, variables="X", times=1:4 )
+
+# Bivariate VAR
+sem = "
+ X -> X, 1, XtoX
+ X -> Y, 1, XtoY
+ Y -> X, 1, YtoX
+ Y -> Y, 1, YtoY
+ X <-> X, 0, sdX
+ Y <-> Y, 0, sdY
+"
+make_dsem_ram( sem=sem, variables=c("X","Y"), times=1:4 )
+
+# Dynamic factor analysis with one factor and two manifest variables
+# (specifies a random-walk for the factor, and miniscule residual SD)
+sem = "
+ factor -> X, 0, loadings1
+ factor -> Y, 0, loadings2
+ factor -> factor, 1, NA, 1
+ X <-> X, 0, NA, 0.01 # Fix at negligible value
+ Y <-> Y, 0, NA, 0.01 # Fix at negligible value
+"
+make_dsem_ram( sem=sem, variables=c("X","Y","factor"), times=1:4 )
+
+# ARIMA(1,1,0)
+sem = "
+ factor -> factor, 1, rho1 # AR1 component
+ X -> X, 1, NA, 1 # Integrated component
+ factor -> X, 0, NA, 1
+ X <-> X, 0, NA, 0.01 # Fix at negligible value
+"
+make_dsem_ram( sem=sem, variables=c("X","factor"), times=1:4 )
+
+# ARIMA(0,0,1)
+sem = "
+ factor -> X, 0, NA, 1
+ factor -> X, 1, rho1 # MA1 component
+ X <-> X, 0, NA, 0.01 # Fix at negligible value
+"
+make_dsem_ram( sem=sem, variables=c("X","factor"), times=1:4 )
+
+}
diff --git a/man/make_ram.Rd b/man/make_ram.Rd
deleted file mode 100644
index 8b54814..0000000
--- a/man/make_ram.Rd
+++ /dev/null
@@ -1,30 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/make_ram.R
-\name{make_ram}
-\alias{make_ram}
-\title{Make a RAM (Reticular Action Model)}
-\usage{
-make_ram(sem, tsdata, covs = NULL, quiet = FALSE, remove_na = TRUE)
-}
-\arguments{
-\item{sem}{structural equation model structure, passed to either \code{\link[sem]{specifyModel}}
-or \code{\link[sem]{specifyEquations}} and then parsed to control
-the set of path coefficients and variance-covariance parameters}
-
-\item{tsdata}{time-series data, as outputted using \code{\link[stats]{ts}}}
-
-\item{quiet}{Boolean indicating whether to run model printing messages to terminal or not;}
-
-\item{remove_na}{Boolean indicating whether to remove NA values from RAM (default) or not.
- \code{remove_NA=FALSE} might be useful for exploration and diagnostics for
- advanced users
-
-Copied and then modified with permission from John Fox under licence GPL (>= 2)}
-}
-\value{
-the standard output from \code{\link[stats]{nlminb}}, except with additional diagnostics and timing info,
- and a new slot containing the output from \code{\link[TMB]{sdreport}}
-}
-\description{
-\code{make_ram} converts SEM arrow notation to \code{ram} describing SEM parameters
-}
diff --git a/man/parse_path.Rd b/man/parse_path.Rd
index 014b17f..01a8eae 100644
--- a/man/parse_path.Rd
+++ b/man/parse_path.Rd
@@ -16,5 +16,5 @@ Tagged-list defining variables and direction for a specified path coefficient
\code{parse_path} is copied from \code{sem::parse.path}
}
\details{
-Copied with permission from John Fox under licence GPL (>= 2)
+Copied from package `sem` under licence GPL (>= 2) with permission from John Fox
}
diff --git a/man/plot.dsem.Rd b/man/plot.dsem.Rd
new file mode 100644
index 0000000..cbd7648
--- /dev/null
+++ b/man/plot.dsem.Rd
@@ -0,0 +1,29 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/dsem.R
+\name{plot.dsem}
+\alias{plot.dsem}
+\title{Simulate dsem}
+\usage{
+\method{plot}{dsem}(x, y, edge_label = c("name", "value"), digits = 2, ...)
+}
+\arguments{
+\item{x}{Output from \code{\link{dsem}}}
+
+\item{y}{Not used}
+
+\item{edge_label}{Whether to plot parameter names or estimated values}
+
+\item{digits}{integer indicating the number of decimal places to be used}
+
+\item{...}{arguments passed to \code{\link[igraph]{plot.igraph}}}
+}
+\value{
+Invisibly returns the output from \code{\link[igraph]{graph_from_data_frame}}
+which was passed to \code{\link[igraph]{plot.igraph}} for plotting.
+}
+\description{
+Plot from a fitted \code{dsem} model
+}
+\details{
+This function coerces output from a graph and then plots the graph.
+}
diff --git a/man/predict.dsem.Rd b/man/predict.dsem.Rd
index c4f0c55..4959cfa 100644
--- a/man/predict.dsem.Rd
+++ b/man/predict.dsem.Rd
@@ -2,7 +2,7 @@
% Please edit documentation in R/dsem.R
\name{predict.dsem}
\alias{predict.dsem}
-\title{Predict variables given new (counterfactual) values of data, or for future or past times}
+\title{predictions using dsem}
\usage{
\method{predict}{dsem}(object, newdata = NULL, type = c("link", "response"), ...)
}
@@ -19,8 +19,15 @@ original fitted values.}
the alternative "response" is on the scale of the response variable.
Thus for a Poisson-distributed variable the default predictions are of log-intensity and type = "response" gives the predicted intensity.}
-\item{...}{Note used}
+\item{...}{Not used}
+}
+\value{
+A matrix of predicted values with dimensions and order corresponding to
+argument \code{newdata} is provided, or \code{tsdata} if not.
+Predictions are provided on either link or response scale, and
+are generated by re-optimizing random effects condition on MLE
+for fixed effects, given those new data.
}
\description{
-predictions using dsem
+Predict variables given new (counterfactual) values of data, or for future or past times
}
diff --git a/man/print.dsem.Rd b/man/print.dsem.Rd
new file mode 100644
index 0000000..9491391
--- /dev/null
+++ b/man/print.dsem.Rd
@@ -0,0 +1,20 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/dsem.R
+\name{print.dsem}
+\alias{print.dsem}
+\title{Print fitted dsem object}
+\usage{
+\method{print}{dsem}(x, ...)
+}
+\arguments{
+\item{x}{Output from \code{\link{dsem}}}
+
+\item{...}{Not used}
+}
+\value{
+No return value, called to provide clean terminal output when calling fitted
+object in terminal.
+}
+\description{
+Prints output from fitted dsem model
+}
diff --git a/man/residuals.dsem.Rd b/man/residuals.dsem.Rd
index d91c7d7..0083996 100644
--- a/man/residuals.dsem.Rd
+++ b/man/residuals.dsem.Rd
@@ -2,7 +2,7 @@
% Please edit documentation in R/dsem.R
\name{residuals.dsem}
\alias{residuals.dsem}
-\title{Calculate residuals for dsem}
+\title{Calculate residuals}
\usage{
\method{residuals}{dsem}(object, type = c("deviance", "response"), ...)
}
@@ -11,8 +11,12 @@
\item{type}{which type of residuals to compute (only option is \code{"deviance"} or \code{"response"} for now)}
-\item{...}{Note used}
+\item{...}{Not used}
+}
+\value{
+A matrix of residuals, with same order and dimensions as argument \code{tsdata}
+that was passed to \code{dsem}.
}
\description{
-Calculate residuals
+Calculate deviance or response residuals for dsem
}
diff --git a/man/simulate.dsem.Rd b/man/simulate.dsem.Rd
index ead19f4..a9fc69d 100644
--- a/man/simulate.dsem.Rd
+++ b/man/simulate.dsem.Rd
@@ -2,13 +2,14 @@
% Please edit documentation in R/dsem.R
\name{simulate.dsem}
\alias{simulate.dsem}
-\title{Simulate from a fitted \code{dsem} model}
+\title{Simulate dsem}
\usage{
\method{simulate}{dsem}(
object,
nsim = 1,
seed = NULL,
- parametric_uncertainty = c("none", "random", "both"),
+ variance = c("none", "random", "both"),
+ resimulate_gmrf = FALSE,
...
)
}
@@ -19,18 +20,30 @@
\item{seed}{random seed}
-\item{parametric_uncertainty}{whether to ignore uncertainty in fixed and
+\item{variance}{whether to ignore uncertainty in fixed and
random effects, include estimation uncertainty in random effects,
or include estimation uncertainty in both fixed and random effects}
+\item{resimulate_gmrf}{whether to resimulate the GMRF based on estimated or
+simulated random effects (determined by argument \code{variance})}
+
\item{...}{Not used}
}
+\value{
+Simulated data, either from \code{obj$simulate} where \code{obj} is the compiled
+TMB object, first simulating a new GMRF and then calling \code{obj$simulate}.
+}
\description{
+Simulate from a fitted \code{dsem} model
+}
+\details{
This function conducts a parametric bootstrap, i.e., simulates new data
conditional upon estimated values for fixed and random effects. The user
can optionally simulate new random effects conditional upon their estimated
covariance, or simulate new fixed and random effects conditional upon their imprecision.
-}
-\details{
-Simulate dsem
+
+Note that \code{simulate} will have no effect on states \code{x_tj} for which there
+is a measurement and when those measurements are fitted using \code{family="fixed"}, unless
+\code{resimulate_gmrf=TRUE}. In this latter case, the GMRF is resimulated given
+estimated path coefficients
}
diff --git a/man/summary.dsem.Rd b/man/summary.dsem.Rd
index 6d187d5..9b3d475 100644
--- a/man/summary.dsem.Rd
+++ b/man/summary.dsem.Rd
@@ -2,7 +2,7 @@
% Please edit documentation in R/dsem.R
\name{summary.dsem}
\alias{summary.dsem}
-\title{Summarize dsem}
+\title{summarize dsem}
\usage{
\method{summary}{dsem}(object, ...)
}
@@ -11,6 +11,42 @@
\item{...}{Not used}
}
+\value{
+Returns a data.frame summarizing estimated path coefficients, containing columns:
+\describe{
+\item{path}{The parsed path coefficient}
+\item{lag}{The lag, where e.g. 1 means the predictor in time t effects the response in time t+1}
+\item{name}{Parameter name}
+\item{start}{Start value if supplied, and NA otherwise}
+\item{parameter}{Parameter number}
+\item{first}{Variable in path treated as predictor}
+\item{second}{Variable in path treated as response}
+\item{direction}{Whether the path is one-headed or two-headed}
+\item{Estimate}{Maximum likelihood estimate}
+\item{Std_Error}{Estimated standard error from the Hessian matrix}
+\item{z_value}{Estimate divided by Std_Error}
+\item{p_value}{P-value associated with z_value using a two-sided Wald test}
+}
+}
\description{
-summarize dsem
+summarize parameters from a fitted dynamic structural equation model
+}
+\details{
+A DSEM is specified using "arrow and lag" notation, which specifies the set of
+path coefficients and exogenous variance parameters to be estimated. Function \code{dsem}
+then estimates the maximum likelihood value for those coefficients and parameters
+by maximizing the log-marginal likelihood. Standard errors for parameters are calculated
+from the matrix of second derivatives of this log-marginal likelihood (the "Hessian matrix").
+
+However, many users will want to associate individual parameters and standard errors
+with the path coefficients that were specified using the "arrow and lag" notation.
+This task is complicated in
+models where some path coefficients or variance parameters are specified to share a single value a priori,
+or were assigned a name of NA and hence assumed to have a fixed value a priori (such that
+these coefficients or parameters have an assigned value but no standard error).
+The \code{summary} function therefore compiles the MLE for coefficients (including duplicating
+values for any path coefficients that assigned the same value) and standard error
+estimates, and outputs those in a table that associates them with the user-supplied path and parameter names.
+It also outputs the z-score and a p-value arising from a two-sided Wald test (i.e.
+comparing the estimate divided by standard error against a standard normal distribution).
}
diff --git a/man/vcov.dsem.Rd b/man/vcov.dsem.Rd
index 26ded4a..76f13cb 100644
--- a/man/vcov.dsem.Rd
+++ b/man/vcov.dsem.Rd
@@ -13,6 +13,11 @@
\item{...}{ignored, for method compatibility}
}
+\value{
+A square matrix containing the estimated covariances among the parameter estimates in the model.
+The dimensions dependend upon the argument \code{which}, to determine whether fixed, random effects,
+or both are outputted.
+}
\description{
extract the covariance of fixed effects, or both fixed and random effects.
}
diff --git a/vignettes/vignette.Rmd b/vignettes/vignette.Rmd
index 8750ec0..1bc4bac 100644
--- a/vignettes/vignette.Rmd
+++ b/vignettes/vignette.Rmd
@@ -9,19 +9,24 @@ vignette: >
%\VignetteEncoding{UTF-8}
---
-```{r, include = FALSE}
+```{r, include = FALSE, warning=FALSE, message=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
+# Install locally
+# devtools::install_local( R'(C:\Users\James.Thorson\Desktop\Git\dsem)', force=TRUE )
# Build
-# setwd(R'(C:\Users\James.Thorson\Desktop\Git\dsem)'); devtools::build_rmd("vignettes/vignette.Rmd")
-# PDF
-# library(rmarkdown); render( "vignettes/vignette.Rmd", pdf_document())
+# setwd(R'(C:\Users\James.Thorson\Desktop\Git\dsem)'); devtools::build_rmd("vignettes/vignette.Rmd"); rmarkdown::render( "vignettes/vignette.Rmd", rmarkdown::pdf_document())
```
-```{r setup, echo=TRUE}
+```{r setup, echo=TRUE, message=FALSE}
library(dsem)
+library(dynlm)
+library(ggplot2)
+library(reshape)
+library(gridExtra)
+library(phylopath)
```
`dsem` is an R package for fitting dynamic structural equation models (DSEMs) with a simple user-interface and generic specification of simultaneous and lagged effects in a non-recursive structure. We here highlight a few features in particular.
@@ -31,8 +36,6 @@ library(dsem)
We first demonstrate that `dsem` gives identical results to `dynlm` for a well-known econometric model, the Klein-1 model.
```{r, echo=TRUE, message=FALSE, fig.width=7, fig.height=5}
-library(dynlm)
-
data(KleinI, package="AER")
TS = ts(data.frame(KleinI, "time"=time(KleinI) - 1931))
@@ -43,17 +46,18 @@ fm_pwage <- dynlm(pwage ~ gnp + L(gnp) + time, data = TS)
# dsem
sem = "
+ # Link, lag, param_name
cprofits -> consumption, 0, a1
- cprofits -> consumption, -1, a2
+ cprofits -> consumption, 1, a2
pwage -> consumption, 0, a3
gwage -> consumption, 0, a3
cprofits -> invest, 0, b1
- cprofits -> invest, -1, b2
+ cprofits -> invest, 1, b2
capital -> invest, 0, b3
gnp -> pwage, 0, c2
- gnp -> pwage, -1, c3
+ gnp -> pwage, 1, c3
time -> pwage, 0, c1
"
tsdata = TS[,c("time","gnp","pwage","cprofits",'consumption',
@@ -61,11 +65,13 @@ tsdata = TS[,c("time","gnp","pwage","cprofits",'consumption',
fit = dsem( sem=sem,
tsdata = tsdata,
newtonsteps = 0,
- quiet = TRUE,
- estimate_delta0 = TRUE )
+ estimate_delta0 = TRUE,
+ control = dsem_control(quiet = TRUE) )
# Compile
-m1 = rbind( summary(fm_cons)$coef[-1,], summary(fm_inv)$coef[-1,], summary(fm_pwage)$coef[-1,] )[,1:2]
+m1 = rbind( summary(fm_cons)$coef[-1,],
+ summary(fm_inv)$coef[-1,],
+ summary(fm_pwage)$coef[-1,] )[,1:2]
m2 = summary(fit$opt$SD)[1:9,]
m = rbind(
data.frame("var"=rownames(m1),m1,"method"="OLS","eq"=rep(c("C","I","Wp"),each=3)),
@@ -74,10 +80,6 @@ m = rbind(
m = cbind(m, "lower"=m$Estimate-m$Std..Error, "upper"=m$Estimate+m$Std..Error )
# ggplot estimates
-library(ggplot2)
-library(reshape)
-library(gridExtra)
-library(phylopath)
longform = melt( as.data.frame(KleinI) )
longform$year = rep( time(KleinI), 9 )
@@ -92,17 +94,53 @@ p2 = ggplot(data=m, aes(x=interaction(var,eq), y=Estimate, color=method)) +
p3 = plot( as_fitted_DAG(fit) ) +
expand_limits(x = c(-0.2,1) )
-p4 = plot( as_fitted_DAG(fit, lag=-1) ) +
+p4 = plot( as_fitted_DAG(fit, lag=1), text_size=4 ) +
expand_limits(x = c(-0.2,1), y = c(-0.2,0) )
-grid.arrange( arrangeGrob(p1, arrangeGrob(p2, p3, p4), ncol=2) )
+p1
+p2
+grid.arrange( arrangeGrob(p3, p4, nrow=2) )
```
Results show that both packages provide (almost) identical estimates and standard errors.
+We can also compare results using the Laplace approximation against those obtained via numerical integration of random effects using MCMC. In this example, MCMC results in somewhat higher estimates of exogenous variance parameters (presumably because those follow a chi-squared distribution with positive skewness), but otherwise the two produce similar estimates.
+
+```{r, echo=TRUE, message=FALSE, fig.width=7, fig.height=5, eval=FALSE}
+library(tmbstan)
+
+# MCMC for both fixed and random effects
+mcmc = tmbstan( fit$obj, init="last.par.best" )
+summary_mcmc = summary(mcmc)
+```
+```{r, echo=FALSE, message=FALSE, fig.width=7, fig.height=5, eval=FALSE}
+saveRDS( summary_mcmc, file=file.path(R'(C:\Users\James.Thorson\Desktop\Git\dsem\inst\tmbstan)',"summary_mcmc.RDS") )
+```
+```{r, echo=FALSE, message=FALSE, fig.width=6, fig.height=4, out.width = "100%", eval=TRUE}
+summary_mcmc = readRDS( file.path(system.file("tmbstan",package="dsem"),"summary_mcmc.RDS") )
+```
+```{r, echo=TRUE, message=FALSE, fig.width=6, fig.height=4, out.width = "100%", eval=TRUE}
+# long-form data frame
+m1 = summary_mcmc$summary[1:17,c('mean','sd')]
+rownames(m1) = paste0( "b", seq_len(nrow(m1)) )
+m2 = summary(fit$opt$SD)[1:17,c('Estimate','Std. Error')]
+m = rbind(
+ data.frame('mean'=m1[,1], 'sd'=m1[,2], 'par'=rownames(m1), "method"="MCMC"),
+ data.frame('mean'=m2[,1], 'sd'=m2[,2], 'par'=rownames(m1), "method"="LA")
+)
+m$lower = m$mean - m$sd
+m$upper = m$mean + m$sd
+
+# plot
+ggplot(data=m, aes(x=par, y=mean, col=method)) +
+ geom_point( position=position_dodge(0.9) ) +
+ geom_errorbar( aes(ymax=as.numeric(upper),ymin=as.numeric(lower)),
+ width=0.25, position=position_dodge(0.9)) #
+```
+
## Comparison with vector autoregressive models
-We next demonstrate that `dsem` gives similar results to a vector autoregressive model (VAM). To do so, we analyze population abundance of wolf and moose populations on Isle Royale from 1959 to 2019, downloaded from their website (Vucetich, JA and Peterson RO. 2012. The population biology of Isle Royale wolves and moose: an overview. URL: www.isleroyalewolf.org).
+We next demonstrate that `dsem` gives similar results to a vector autoregressive (VAR) model. To do so, we analyze population abundance of wolf and moose populations on Isle Royale from 1959 to 2019, downloaded from their website (Vucetich, JA and Peterson RO. 2012. The population biology of Isle Royale wolves and moose: an overview. URL: www.isleroyalewolf.org).
This dataset was previously analyzed by in Chapter 14 of the User Manual for the R-package MARSS (Holmes, E. E., M. D. Scheuerell, and E. J. Ward (2023) Analysis of multivariate time-series using the MARSS package. Version 3.11.8. NOAA Fisheries,
Northwest Fisheries Science Center, 2725 Montlake Blvd E., Seattle, WA 98112, DOI: 10.5281/zenodo.5781847).
@@ -112,21 +150,26 @@ Here, we compare fits using `dsem` with `dynlm`, as well as a vector autoregress
```{r, echo=TRUE, message=FALSE, fig.width=7, fig.height=5}
data(isle_royale)
data = ts( log(isle_royale[,2:3]), start=1959)
-family = c("fixed","fixed")
sem = "
- wolves -> wolves, -1, arW
- moose -> wolves, -1, MtoW
- wolves -> moose, -1, WtoM
- moose -> moose, -1, arM
+ # Link, lag, param_name
+ wolves -> wolves, 1, arW
+ moose -> wolves, 1, MtoW
+ wolves -> moose, 1, WtoM
+ moose -> moose, 1, arM
"
# initial first without delta0 (to improve starting values)
-fit0 = dsem( sem=sem, tsdata=data, estimate_delta0=FALSE,
- quiet=TRUE, getsd=FALSE, family=family )
+fit0 = dsem( sem = sem,
+ tsdata = data,
+ estimate_delta0 = FALSE,
+ control = dsem_control(quiet=TRUE),
+ getsd=FALSE )
# Refit with delta0
-fit = dsem( sem=sem, tsdata=data, estimate_delta0=TRUE,
- quiet=TRUE, parameters=fit0$obj$env$parList(),
- family=family, getJointPrecision = TRUE )
+fit = dsem( sem = sem,
+ tsdata = data,
+ estimate_delta0 = TRUE,
+ control = dsem_control( quiet=TRUE,
+ parameters = fit0$obj$env$parList()) )
# dynlm
fm_wolf = dynlm( wolves ~ 1 + L(wolves) + L(moose), data=data ) #
@@ -182,7 +225,7 @@ p2 = ggplot(data=m, aes(x=interaction(var,eq), y=Estimate, color=method)) +
geom_point( position=position_dodge(0.9) ) +
geom_errorbar( aes(ymax=as.numeric(upper),ymin=as.numeric(lower)),
width=0.25, position=position_dodge(0.9)) #
-p3 = plot( as_fitted_DAG(fit, lag=-1), rotation=0 ) +
+p3 = plot( as_fitted_DAG(fit, lag=1), rotation=0 ) +
geom_edge_loop( aes( label=round(weight,2), direction=0)) + #arrow=arrow(), , angle_calc="along", label_dodge=grid::unit(10,"points") )
expand_limits(x = c(-0.1,0) )
@@ -204,6 +247,7 @@ family = rep('fixed', ncol(bering_sea))
# Specify model
sem = "
+ # Link, lag, param_name
log_seaice -> log_CP, 0, seaice_to_CP
log_CP -> log_Cfall, 0, CP_to_Cfall
log_CP -> log_Esummer, 0, CP_to_E
@@ -213,33 +257,27 @@ sem = "
log_Cfall -> log_PercentCop, 0, Cfall_to_Scop
log_SSB -> log_RperS, 0, SSB_to_RperS
- #log_seaice <-> log_seaice, 0, var1, 0.001
- #log_CP <-> log_CP,0, var2, 0.001
- #log_Cspring <-> log_Cspring, 0, var3, 0.001
- #log_Cfall <-> log_Cfall, 0, var4, 0.001
- #log_Esummer <-> log_Esummer, 0, var5, 0.001
- #log_SSB <-> log_SSB, 0, var6, 0.001
- #log_RperS <-> log_RperS, 0, var7, 0.001
- #log_PercentEuph <-> log_PercentEuph, 0, var8, 0.001
- #log_PercentCop <-> log_PercentCop, 0, var9, 0.001
-
- log_seaice -> log_seaice, -1, AR1, 0.001
- log_CP -> log_CP, -1, AR2, 0.001
- log_Cspring -> log_Cspring, -1, AR3, 0.001
- log_Cfall -> log_Cfall, -1, AR4, 0.001
- log_Esummer -> log_Esummer, -1, AR5, 0.001
- log_SSB -> log_SSB, -1, AR6, 0.001
- log_RperS -> log_RperS, -1, AR7, 0.001
- log_PercentEuph -> log_PercentEuph, -1, AR8, 0.001
- log_PercentCop -> log_PercentCop, -1, AR9, 0.001
+ log_seaice -> log_seaice, 1, AR1, 0.001
+ log_CP -> log_CP, 1, AR2, 0.001
+ log_Cspring -> log_Cspring, 1, AR3, 0.001
+ log_Cfall -> log_Cfall, 1, AR4, 0.001
+ log_Esummer -> log_Esummer, 1, AR5, 0.001
+ log_SSB -> log_SSB, 1, AR6, 0.001
+ log_RperS -> log_RperS, 1, AR7, 0.001
+ log_PercentEuph -> log_PercentEuph, 1, AR8, 0.001
+ log_PercentCop -> log_PercentCop, 1, AR9, 0.001
"
# Fit
-fit = dsem( sem=sem, tsdata=Z, family=family, use_REML=FALSE, quiet=TRUE )
+fit = dsem( sem = sem,
+ tsdata = Z,
+ family = family,
+ control = dsem_control(use_REML=FALSE, quiet=TRUE) )
ParHat = fit$obj$env$parList()
# summary( fit )
# Timeseries plot
+oldpar <- par(no.readonly = TRUE)
par( mfcol=c(3,3), mar=c(2,2,2,0), mgp=c(2,0.5,0), tck=-0.02 )
for(i in 1:ncol(bering_sea)){
tmp = bering_sea[,i,drop=FALSE]
@@ -255,6 +293,7 @@ for(i in 1:ncol(bering_sea)){
polygon( x=c(rownames(bering_sea),rev(rownames(bering_sea))),
y=c(tmp[,3],rev(tmp[,4])), col=rgb(0,0,1,0.2), border=NA )
}
+par(oldpar)
#
library(phylopath)
@@ -347,69 +386,71 @@ sem = "
log_Otter_Count_SIREN_CEN -> log_Kelp_SIREN_CEN, 0, x4
# AR1
- Pycno_CANNERY_DC -> Pycno_CANNERY_DC, -1, ar1
- log_Urchins_CANNERY_DC -> log_Urchins_CANNERY_DC, -1, ar2
- log_Otter_Count_CANNERY_DC -> log_Otter_Count_CANNERY_DC, -1, ar3
- log_Kelp_CANNERY_DC -> log_Kelp_CANNERY_DC, -1, ar4
-
- Pycno_CANNERY_UC -> Pycno_CANNERY_UC, -1, ar1
- log_Urchins_CANNERY_UC -> log_Urchins_CANNERY_UC, -1, ar2
- log_Otter_Count_CANNERY_UC -> log_Otter_Count_CANNERY_UC, -1, ar3
- log_Kelp_CANNERY_UC -> log_Kelp_CANNERY_UC, -1, ar4
-
- Pycno_HOPKINS_DC -> Pycno_HOPKINS_DC, -1, ar1
- log_Urchins_HOPKINS_DC -> log_Urchins_HOPKINS_DC, -1, ar2
- log_Otter_Count_HOPKINS_DC -> log_Otter_Count_HOPKINS_DC, -1, ar3
- log_Kelp_HOPKINS_DC -> log_Kelp_HOPKINS_DC, -1, ar4
-
- Pycno_HOPKINS_UC -> Pycno_HOPKINS_UC, -1, ar1
- log_Urchins_HOPKINS_UC -> log_Urchins_HOPKINS_UC, -1, ar2
- log_Otter_Count_HOPKINS_UC -> log_Otter_Count_HOPKINS_UC, -1, ar3
- log_Kelp_HOPKINS_UC -> log_Kelp_HOPKINS_UC, -1, ar4
-
- Pycno_LOVERS_DC -> Pycno_LOVERS_DC, -1, ar1
- log_Urchins_LOVERS_DC -> log_Urchins_LOVERS_DC, -1, ar2
- log_Otter_Count_LOVERS_DC -> log_Otter_Count_LOVERS_DC, -1, ar3
- log_Kelp_LOVERS_DC -> log_Kelp_LOVERS_DC, -1, ar4
-
- Pycno_LOVERS_UC -> Pycno_LOVERS_UC, -1, ar1
- log_Urchins_LOVERS_UC -> log_Urchins_LOVERS_UC, -1, ar2
- log_Otter_Count_LOVERS_UC -> log_Otter_Count_LOVERS_UC, -1, ar3
- log_Kelp_LOVERS_UC -> log_Kelp_LOVERS_UC, -1, ar4
-
- Pycno_MACABEE_DC -> Pycno_MACABEE_DC, -1, ar1
- log_Urchins_MACABEE_DC -> log_Urchins_MACABEE_DC, -1, ar2
- log_Otter_Count_MACABEE_DC -> log_Otter_Count_MACABEE_DC, -1, ar3
- log_Kelp_MACABEE_DC -> log_Kelp_MACABEE_DC, -1, ar4
-
- Pycno_MACABEE_UC -> Pycno_MACABEE_UC, -1, ar1
- log_Urchins_MACABEE_UC -> log_Urchins_MACABEE_UC, -1, ar2
- log_Otter_Count_MACABEE_UC -> log_Otter_Count_MACABEE_UC, -1, ar3
- log_Kelp_MACABEE_UC -> log_Kelp_MACABEE_UC, -1, ar4
-
- Pycno_OTTER_PT_DC -> Pycno_OTTER_PT_DC, -1, ar1
- log_Urchins_OTTER_PT_DC -> log_Urchins_OTTER_PT_DC, -1, ar2
- log_Otter_Count_OTTER_PT_DC -> log_Otter_Count_OTTER_PT_DC, -1, ar3
- log_Kelp_OTTER_PT_DC -> log_Kelp_OTTER_PT_DC, -1, ar4
-
- Pycno_OTTER_PT_UC -> Pycno_OTTER_PT_UC, -1, ar1
- log_Urchins_OTTER_PT_UC -> log_Urchins_OTTER_PT_UC, -1, ar2
- log_Otter_Count_OTTER_PT_UC -> log_Otter_Count_OTTER_PT_UC, -1, ar3
- log_Kelp_OTTER_PT_UC -> log_Kelp_OTTER_PT_UC, -1, ar4
-
- Pycno_PINOS_CEN -> Pycno_PINOS_CEN, -1, ar1
- log_Urchins_PINOS_CEN -> log_Urchins_PINOS_CEN, -1, ar2
- log_Otter_Count_PINOS_CEN -> log_Otter_Count_PINOS_CEN, -1, ar3
- log_Kelp_PINOS_CEN -> log_Kelp_PINOS_CEN, -1, ar4
-
- Pycno_SIREN_CEN -> Pycno_SIREN_CEN, -1, ar1
- log_Urchins_SIREN_CEN -> log_Urchins_SIREN_CEN, -1, ar2
- log_Otter_Count_SIREN_CEN -> log_Otter_Count_SIREN_CEN, -1, ar3
- log_Kelp_SIREN_CEN -> log_Kelp_SIREN_CEN, -1, ar4
+ Pycno_CANNERY_DC -> Pycno_CANNERY_DC, 1, ar1
+ log_Urchins_CANNERY_DC -> log_Urchins_CANNERY_DC, 1, ar2
+ log_Otter_Count_CANNERY_DC -> log_Otter_Count_CANNERY_DC, 1, ar3
+ log_Kelp_CANNERY_DC -> log_Kelp_CANNERY_DC, 1, ar4
+
+ Pycno_CANNERY_UC -> Pycno_CANNERY_UC, 1, ar1
+ log_Urchins_CANNERY_UC -> log_Urchins_CANNERY_UC, 1, ar2
+ log_Otter_Count_CANNERY_UC -> log_Otter_Count_CANNERY_UC, 1, ar3
+ log_Kelp_CANNERY_UC -> log_Kelp_CANNERY_UC, 1, ar4
+
+ Pycno_HOPKINS_DC -> Pycno_HOPKINS_DC, 1, ar1
+ log_Urchins_HOPKINS_DC -> log_Urchins_HOPKINS_DC, 1, ar2
+ log_Otter_Count_HOPKINS_DC -> log_Otter_Count_HOPKINS_DC, 1, ar3
+ log_Kelp_HOPKINS_DC -> log_Kelp_HOPKINS_DC, 1, ar4
+
+ Pycno_HOPKINS_UC -> Pycno_HOPKINS_UC, 1, ar1
+ log_Urchins_HOPKINS_UC -> log_Urchins_HOPKINS_UC, 1, ar2
+ log_Otter_Count_HOPKINS_UC -> log_Otter_Count_HOPKINS_UC, 1, ar3
+ log_Kelp_HOPKINS_UC -> log_Kelp_HOPKINS_UC, 1, ar4
+
+ Pycno_LOVERS_DC -> Pycno_LOVERS_DC, 1, ar1
+ log_Urchins_LOVERS_DC -> log_Urchins_LOVERS_DC, 1, ar2
+ log_Otter_Count_LOVERS_DC -> log_Otter_Count_LOVERS_DC, 1, ar3
+ log_Kelp_LOVERS_DC -> log_Kelp_LOVERS_DC, 1, ar4
+
+ Pycno_LOVERS_UC -> Pycno_LOVERS_UC, 1, ar1
+ log_Urchins_LOVERS_UC -> log_Urchins_LOVERS_UC, 1, ar2
+ log_Otter_Count_LOVERS_UC -> log_Otter_Count_LOVERS_UC, 1, ar3
+ log_Kelp_LOVERS_UC -> log_Kelp_LOVERS_UC, 1, ar4
+
+ Pycno_MACABEE_DC -> Pycno_MACABEE_DC, 1, ar1
+ log_Urchins_MACABEE_DC -> log_Urchins_MACABEE_DC, 1, ar2
+ log_Otter_Count_MACABEE_DC -> log_Otter_Count_MACABEE_DC, 1, ar3
+ log_Kelp_MACABEE_DC -> log_Kelp_MACABEE_DC, 1, ar4
+
+ Pycno_MACABEE_UC -> Pycno_MACABEE_UC, 1, ar1
+ log_Urchins_MACABEE_UC -> log_Urchins_MACABEE_UC, 1, ar2
+ log_Otter_Count_MACABEE_UC -> log_Otter_Count_MACABEE_UC, 1, ar3
+ log_Kelp_MACABEE_UC -> log_Kelp_MACABEE_UC, 1, ar4
+
+ Pycno_OTTER_PT_DC -> Pycno_OTTER_PT_DC, 1, ar1
+ log_Urchins_OTTER_PT_DC -> log_Urchins_OTTER_PT_DC, 1, ar2
+ log_Otter_Count_OTTER_PT_DC -> log_Otter_Count_OTTER_PT_DC, 1, ar3
+ log_Kelp_OTTER_PT_DC -> log_Kelp_OTTER_PT_DC, 1, ar4
+
+ Pycno_OTTER_PT_UC -> Pycno_OTTER_PT_UC, 1, ar1
+ log_Urchins_OTTER_PT_UC -> log_Urchins_OTTER_PT_UC, 1, ar2
+ log_Otter_Count_OTTER_PT_UC -> log_Otter_Count_OTTER_PT_UC, 1, ar3
+ log_Kelp_OTTER_PT_UC -> log_Kelp_OTTER_PT_UC, 1, ar4
+
+ Pycno_PINOS_CEN -> Pycno_PINOS_CEN, 1, ar1
+ log_Urchins_PINOS_CEN -> log_Urchins_PINOS_CEN, 1, ar2
+ log_Otter_Count_PINOS_CEN -> log_Otter_Count_PINOS_CEN, 1, ar3
+ log_Kelp_PINOS_CEN -> log_Kelp_PINOS_CEN, 1, ar4
+
+ Pycno_SIREN_CEN -> Pycno_SIREN_CEN, 1, ar1
+ log_Urchins_SIREN_CEN -> log_Urchins_SIREN_CEN, 1, ar2
+ log_Otter_Count_SIREN_CEN -> log_Otter_Count_SIREN_CEN, 1, ar3
+ log_Kelp_SIREN_CEN -> log_Kelp_SIREN_CEN, 1, ar4
"
# Fit model
-fit = dsem( sem=sem, tsdata=Z, use_REML=FALSE, quiet=TRUE )
+fit = dsem( sem = sem,
+ tsdata = Z,
+ control = dsem_control(use_REML=FALSE, quiet=TRUE) )
# summary( fit )
#
diff --git a/vignettes/vignette.pdf b/vignettes/vignette.pdf
index 74f37f3..52c51ec 100644
Binary files a/vignettes/vignette.pdf and b/vignettes/vignette.pdf differ