From 58f67181d6bfa8107ee8d1c5d15293addb503bd7 Mon Sep 17 00:00:00 2001
From: JaroSant <74154059+JaroSant@users.noreply.github.com>
Date: Wed, 5 Oct 2022 17:01:55 +0100
Subject: [PATCH] Initial commit
---
.gitattributes | 2 +
LICENCE | 684 +++
Makefile | 18 +
Polynomial.cpp | 1578 ++++++
Polynomial.h | 196 +
PolynomialRootFinder.cpp | 1362 ++++++
PolynomialRootFinder.h | 136 +
PolynomialTest.cpp | 450 ++
R-plotter.r | 19 +
README.md | 34 +
WrightFisher.cpp | 9819 ++++++++++++++++++++++++++++++++++++++
WrightFisher.h | 280 ++
config.cfg | 42 +
configBridge.cfg | 48 +
configDiffusion.cfg | 36 +
configHorseCoat.cfg | 63 +
main.cpp | 1011 ++++
myHelpers.cpp | 12 +
myHelpers.h | 94 +
run.sh | 7 +
20 files changed, 15891 insertions(+)
create mode 100644 .gitattributes
create mode 100644 LICENCE
create mode 100644 Makefile
create mode 100644 Polynomial.cpp
create mode 100644 Polynomial.h
create mode 100644 PolynomialRootFinder.cpp
create mode 100644 PolynomialRootFinder.h
create mode 100644 PolynomialTest.cpp
create mode 100644 R-plotter.r
create mode 100644 README.md
create mode 100644 WrightFisher.cpp
create mode 100644 WrightFisher.h
create mode 100644 config.cfg
create mode 100644 configBridge.cfg
create mode 100644 configDiffusion.cfg
create mode 100644 configHorseCoat.cfg
create mode 100644 main.cpp
create mode 100644 myHelpers.cpp
create mode 100644 myHelpers.h
create mode 100644 run.sh
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..dfe0770
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# Auto detect text files and perform LF normalization
+* text=auto
diff --git a/LICENCE b/LICENCE
new file mode 100644
index 0000000..a3fdb96
--- /dev/null
+++ b/LICENCE
@@ -0,0 +1,684 @@
+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/Makefile b/Makefile
new file mode 100644
index 0000000..857688a
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,18 @@
+CC := g++
+CFLAGS := -Wall -Wextra -std=c++11 -O3 # -g
+LDFLAGS := -I/home/ubuntu/Desktop/boost_1_78_0 -I/home/ubuntu/Desktop/EWF /usr/local/lib/libconfig++.a
+
+#Make sure LDFLAGS points towards the locations where:
+
+# 1. your boost library resides(e.g.'/home/ubuntu/Desktop/boost_1_78_0')
+# 2. the source files for the program reside(e.g.'/home/ubuntu/Desktop/EWF')
+# 3. the library libconfig ++.a resides(e.g.'/usr/local/lib/libconfig++.a')
+
+PROGRAMS := main
+
+all: $(PROGRAMS)
+
+main: main.cpp WrightFisher.cpp myHelpers.cpp Polynomial.cpp PolynomialRootFinder.cpp
+ $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
+
+clean: rm -f *.o $(PROGRAMS)
diff --git a/Polynomial.cpp b/Polynomial.cpp
new file mode 100644
index 0000000..4de2623
--- /dev/null
+++ b/Polynomial.cpp
@@ -0,0 +1,1578 @@
+//=======================================================================
+// Copyright (C) 2003-2013 William Hallahan
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software,
+// and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//=======================================================================
+
+//**********************************************************************
+// File: Polynomial.cpp
+// Author: Bill Hallahan
+// Date: January 30, 2003
+//
+// Abstract:
+//
+// This file contains the implementation for class Polynomial.
+//
+//**********************************************************************
+
+#include "Polynomial.h"
+#include "PolynomialRootFinder.h"
+#include
+#include
+#include
+#include
+#include
+
+//======================================================================
+// Constructor: Polynomial::Polynomial
+//======================================================================
+
+Polynomial::Polynomial() : m_degree(-1), m_coefficient_vector_ptr(NULL) {
+ SetToScalar(0.0);
+}
+
+//======================================================================
+// Constructor: Polynomial::Polynomial
+//
+// Input:
+//
+// scalar A scalar value.
+//
+//======================================================================
+
+Polynomial::Polynomial(double scalar)
+ : m_degree(-1), m_coefficient_vector_ptr(NULL) {
+ SetToScalar(scalar);
+}
+
+//======================================================================
+// Constructor: Polynomial::Polynomial
+//
+// Input:
+//
+// x_coefficient The coefficient for x term of the
+// polynomial.
+//
+// scalar The scalar value of the polynomial.
+//
+// Where the resulting polynomial will be in the form of:
+//
+// x_coefficient * x + scalar = 0
+//
+// degree The degree of the polynomial.
+//
+//======================================================================
+
+Polynomial::Polynomial(double x_coefficient, double scalar)
+ : m_degree(-1), m_coefficient_vector_ptr(NULL) {
+ SetToFirstOrderPolynomial(x_coefficient, scalar);
+}
+
+//======================================================================
+// Constructor: Polynomial::Polynomial
+//
+// Input:
+//
+// x_squared_coefficient The coefficient for x * x term of
+// the quadratic polynomial.
+//
+// x_coefficient The coefficient for x term of the
+// quadratic polynomial.
+//
+// scalar The scalar value of the quadratic
+// polynomial.
+//
+// Where the resulting polynomial will be in the form of:
+//
+// x_squared_coefficient * x^2 + x_coefficient * x + scalar = 0
+//
+// degree The degree of the polynomial.
+//
+//======================================================================
+
+Polynomial::Polynomial(double x_squared_coefficient, double x_coefficient,
+ double scalar)
+ : m_degree(-1), m_coefficient_vector_ptr(NULL) {
+ SetToQuadraticPolynomial(x_squared_coefficient, x_coefficient, scalar);
+}
+
+//======================================================================
+// Constructor: Polynomial::Polynomial
+//
+// Input:
+//
+// coefficient_vector_ptr The vector of coefficients in order
+// of increasing powers.
+//
+// degree The degree of the polynomial.
+//
+//======================================================================
+
+Polynomial::Polynomial(double *coefficient_vector_ptr, int degree)
+ : m_degree(-1), m_coefficient_vector_ptr(NULL) {
+ SetCoefficients(coefficient_vector_ptr, degree);
+}
+
+//======================================================================
+// Copy Constructor: Polynomial::Polynomial
+//======================================================================
+
+Polynomial::Polynomial(const Polynomial &polynomial)
+ : m_degree(-1), m_coefficient_vector_ptr(NULL) {
+ Copy(polynomial);
+}
+
+//======================================================================
+// Destructor: Polynomial::~Polynomial
+//======================================================================
+
+Polynomial::~Polynomial() {}
+
+//======================================================================
+// Member Function: Polynomial::SetCoefficients
+//
+// Abstract:
+//
+// This method sets the polynomial coefficients.
+//
+//
+// Input:
+//
+// coefficient_vector_ptr The vector of coefficients in order
+// of increasing powers.
+//
+// degree The degree of the polynomial.
+//
+//
+// Return Value:
+//
+// The function has no return value.
+//
+//======================================================================
+
+void Polynomial::SetCoefficients(double *coefficient_vector_ptr, int degree) {
+ assert(degree >= 0);
+
+ m_degree = degree;
+
+ SetLength(m_degree + 1, false);
+
+ int ii = 0;
+
+ for (ii = 0; ii <= m_degree; ++ii) {
+ m_coefficient_vector_ptr[ii] = coefficient_vector_ptr[ii];
+ }
+
+ AdjustPolynomialDegree();
+}
+
+//======================================================================
+// Member Function: Polynomial::SetToScalar
+//
+// Abstract:
+//
+// This method sets the polynomial to be a scalar.
+// The polynomial degree is set to 0 in this method.
+//
+//
+// Input:
+//
+// scalar A scalar value
+//
+// Return Value:
+//
+// The function has no return value.
+//
+//======================================================================
+
+void Polynomial::SetToScalar(double scalar) { SetCoefficients(&scalar, 0); }
+
+//======================================================================
+// Member Function: Polynomial::SetToFirstOrderPolynomial
+//
+// Input:
+//
+// x_coefficient The coefficient for x term of the
+// polynomial.
+//
+// scalar The scalar value of the polynomial.
+//
+// Where the resulting polynomial will be in the form of:
+//
+// x_coefficient * x + scalar = 0
+//
+// degree The degree of the polynomial.
+//
+//======================================================================
+
+void Polynomial::SetToFirstOrderPolynomial(double x_coefficient,
+ double scalar) {
+ double coefficient_array[2];
+ coefficient_array[0] = scalar;
+ coefficient_array[1] = x_coefficient;
+ SetCoefficients(&coefficient_array[0], 1);
+}
+
+//======================================================================
+// Member Function: Polynomial::SetToQuadraticPolynomial
+//
+// Input:
+//
+// x_squared_coefficient The coefficient for x * x term of
+// the quadratic polynomial.
+//
+// x_coefficient The coefficient for x term of the
+// quadratic polynomial.
+//
+// scalar The scalar value of the quadratic
+// polynomial.
+//
+// Where the resulting polynomial will be in the form of:
+//
+// x_squared_coefficient * x^2 + x_coefficient * x + scalar = 0
+//
+// degree The degree of the polynomial.
+//
+//======================================================================
+
+void Polynomial::SetToQuadraticPolynomial(double x_squared_coefficient,
+ double x_coefficient, double scalar) {
+ double coefficient_array[3];
+ coefficient_array[0] = scalar;
+ coefficient_array[1] = x_coefficient;
+ coefficient_array[2] = x_squared_coefficient;
+ SetCoefficients(&coefficient_array[0], 2);
+}
+
+//======================================================================
+// Member Function: Polynomial::EvaluateReal
+//
+// Abstract:
+//
+// This method evaluates the polynomial using the passed real
+// value x. The algorithm used is Horner's method.
+//
+//
+// Input:
+//
+// xr A real value.
+//
+//
+// Return Value:
+//
+// This function returns a value of type 'double' that is equal
+// to the polynomial evaluated at the passed value x.
+//
+//======================================================================
+
+double Polynomial::EvaluateReal(double xr) const {
+ assert(m_degree >= 0);
+
+ double pr = m_coefficient_vector_ptr[m_degree];
+ int i = 0;
+
+ for (i = m_degree - 1; i >= 0; --i) {
+ pr = pr * xr + m_coefficient_vector_ptr[i];
+ }
+
+ return pr;
+}
+
+//======================================================================
+// Member Function: Polynomial::EvaluateReal
+//
+// Abstract:
+//
+// This method evaluates the polynomial using the passed real
+// value x. The algorithm used is Horner's method.
+//
+//
+// Input:
+//
+// xr A real value.
+//
+// dr A reference to a double which contains the real term
+// that the polynomial derivative evaluates to.
+//
+// Return Value:
+//
+// This function returns a value of type 'double' that is equal
+// to the polynomial evaluated at the passed value x.
+//
+//======================================================================
+
+double Polynomial::EvaluateReal(double xr, double &dr) const {
+ assert(m_degree >= 0);
+
+ double pr = m_coefficient_vector_ptr[m_degree];
+ dr = pr;
+
+ int i = 0;
+
+ for (i = m_degree - 1; i > 0; --i) {
+ pr = pr * xr + m_coefficient_vector_ptr[i];
+ dr = dr * xr + pr;
+ }
+
+ pr = pr * xr + m_coefficient_vector_ptr[0];
+
+ return pr;
+}
+
+//======================================================================
+// Member Function: Polynomial::EvaluateImaginary
+//
+// Abstract:
+//
+// This function evaluates the value of a polynomial for a
+// specified pure imaginary value xi. The polynomial value
+// is evaluated by Horner's method.
+//
+//
+// Input:
+//
+// xi A double which equals the imaginary term used to
+// evaluate the polynomial.
+//
+// Outputs:
+//
+// pr A reference to a double which contains the real term
+// that the polynomial evaluates to.
+//
+// pi A reference to a double which contains the imaginary
+// term that the polynomial evaluates to.
+//
+// Return Value:
+//
+// This function has no return value.
+//
+//======================================================================
+
+void Polynomial::EvaluateImaginary(double xi, double &pr, double &pi) const {
+ assert(m_degree >= 0);
+
+ pr = m_coefficient_vector_ptr[m_degree];
+ pi = 0;
+
+ int i = 0;
+
+ for (i = m_degree - 1; i >= 0; --i) {
+ double temp = -pi * xi + m_coefficient_vector_ptr[i];
+ pi = pr * xi;
+ pr = temp;
+ }
+
+ return;
+}
+
+//======================================================================
+// Member Function: Polynomial::EvaluateComplex
+//
+// Abstract:
+//
+// This function evaluates the value of a polynomial for a
+// specified complex value xr + i xi. The polynomial value
+// is evaluated by Horner's method.
+//
+//
+// Input:
+//
+// xr A double which equals the real term used to evaluate
+// the polynomial.
+//
+// xi A double which equals the imaginary term used to
+// evaluate the polynomial.
+//
+// Outputs:
+//
+// pr A reference to a double which contains the real term
+// that the polynomial evaluates to.
+//
+// pi A reference to a double which contains the imaginary
+// term that the polynomial evaluates to.
+//
+// Return Value:
+//
+// This function has no return value.
+//
+//======================================================================
+
+void Polynomial::EvaluateComplex(double xr, double xi, double &pr,
+ double &pi) const {
+ assert(m_degree >= 0);
+
+ pr = m_coefficient_vector_ptr[m_degree];
+ pi = 0;
+
+ int i = 0;
+
+ for (i = m_degree - 1; i >= 0; --i) {
+ double temp = pr * xr - pi * xi + m_coefficient_vector_ptr[i];
+ pi = pr * xi + pi * xr;
+ pr = temp;
+ }
+
+ return;
+}
+
+//======================================================================
+// Member Function: Polynomial::EvaluateComplex
+//
+// Abstract:
+//
+// This function evaluates the value of a polynomial and the
+// value of the polynomials derivative for a specified complex
+// value xr + i xi. The polynomial value is evaluated by
+// Horner's method. The combination of the polynomial evaluation
+// and the derivative evaluation is known as the Birge-Vieta method.
+//
+//
+// Input:
+//
+// xr A double which equals the real term used to evaluate
+// the polynomial.
+//
+// xi A double which equals the imaginary term used to
+// evaluate the polynomial.
+//
+// Outputs:
+//
+// pr A reference to a double which contains the real term
+// that the polynomial evaluates to.
+//
+// pi A reference to a double which contains the imaginary
+// term that the polynomial evaluates to.
+//
+// dr A reference to a double which contains the real term
+// that the polynomial derivative evaluates to.
+//
+// di A reference to a double which contains the imaginary
+// term that the polynomial derivative evaluates to.
+//
+// Return Value:
+//
+// This function has no return value.
+//
+//======================================================================
+
+void Polynomial::EvaluateComplex(double xr, double xi, double &pr, double &pi,
+ double &dr, double &di) const {
+ assert(m_degree >= 0);
+
+ pr = m_coefficient_vector_ptr[m_degree];
+ pi = 0;
+ dr = pr;
+ di = 0;
+
+ double temp = 0.0;
+ int i = 0;
+
+ for (i = m_degree - 1; i > 0; --i) {
+ temp = pr * xr - pi * xi + m_coefficient_vector_ptr[i];
+ pi = pr * xi + pi * xr;
+ pr = temp;
+
+ temp = dr * xr - di * xi + pr;
+ di = dr * xi + di * xr + pi;
+ dr = temp;
+ }
+
+ temp = pr * xr - pi * xi + m_coefficient_vector_ptr[0];
+ pi = pr * xi + pi * xr;
+ pr = temp;
+
+ return;
+}
+
+//======================================================================
+// Member Function: Polynomial::Derivative
+//
+// Abstract:
+//
+// This method calculates the derivative polynomial.
+//
+//
+// Input:
+//
+// None
+//
+// Return Value:
+//
+// This function returns a polynomial that is the derivative
+// of this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::Derivative() const {
+ Polynomial derivative_polynomial;
+
+ //------------------------------------------------------------------
+ // If this polynomial is just a scalar, i.e. it is of degree
+ // zero then the derivative is zero.
+ //------------------------------------------------------------------
+
+ assert(m_degree >= 0);
+
+ if (m_degree > 0) {
+ //--------------------------------------------------------------
+ // Set the size of the buffer for the derivative polynomial.
+ //--------------------------------------------------------------
+
+ derivative_polynomial.SetLength(m_degree);
+
+ //--------------------------------------------------------------
+ // Set the degree of the derivative polynomial.
+ //--------------------------------------------------------------
+
+ derivative_polynomial.m_degree = m_degree - 1;
+
+ //--------------------------------------------------------------
+ // Calculate the derivative polynomial.
+ //--------------------------------------------------------------
+
+ double *temp_ptr = derivative_polynomial.m_coefficient_vector_ptr;
+
+ for (int i = m_degree; i > 0; --i) {
+ temp_ptr[i - 1] = (double)(i)*m_coefficient_vector_ptr[i];
+ }
+ } else {
+ derivative_polynomial = 0.0;
+ }
+
+ return derivative_polynomial;
+}
+
+//======================================================================
+// Member Function: Polynomial::Integral
+//
+// Abstract:
+//
+// This method calculates the integral polynomial.
+//
+//
+// Input:
+//
+// None
+//
+// Return Value:
+//
+// This function returns a polynomial that is the integral
+// of this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::Integral() const {
+ Polynomial integral_polynomial;
+
+ //------------------------------------------------------------------
+ // Set the size of the buffer for the integral polynomial.
+ //------------------------------------------------------------------
+
+ assert(m_degree >= 0);
+
+ integral_polynomial.SetLength(m_degree + 2);
+
+ //------------------------------------------------------------------
+ // Set the degree of the integral polynomial.
+ //------------------------------------------------------------------
+
+ integral_polynomial.m_degree = m_degree + 1;
+
+ //------------------------------------------------------------------
+ // Calculate the integral polynomial.
+ //------------------------------------------------------------------
+
+ double *temp_ptr = integral_polynomial.m_coefficient_vector_ptr;
+ int i = 0;
+
+ for (i = m_degree; i > 0; --i) {
+ temp_ptr[i + 1] = m_coefficient_vector_ptr[i] / (double)(i + 1);
+ }
+
+ return integral_polynomial;
+}
+
+//======================================================================
+// Member Function: Polynomial::Degree
+//
+// Abstract:
+//
+// This method gets the polynomial degree.
+//
+//
+// Input:
+//
+// None.
+//
+//
+// Return Value:
+//
+// This function returns a value of type 'int' that is the
+// degree of the polynomial.
+//
+//======================================================================
+
+int Polynomial::Degree() const { return m_degree; }
+
+//======================================================================
+// Member Function: Polynomial::FindRoots
+//
+// Abstract:
+//
+// This method determines the roots of a polynomial which has
+// real coefficients.
+//
+//
+// Input:
+//
+//
+// real_zero_vector_ptr A double precision vector that will
+// contain the real parts of the roots
+// of the polynomial when this method
+// returns.
+//
+// imaginary_zero_vector_ptr A double precision vector that will
+// contain the real parts of the roots
+// of the polynomial when this method
+// returns.
+//
+// roots_found_ptr A pointer to an integer that will
+// equal the number of roots found when
+// this method returns. If the method
+// returns SUCCESS then this value will
+// always equal the degree of the
+// polynomial.
+//
+// Return Value:
+//
+// This function returns an enum value of type
+// 'PolynomialRootFinder::RootStatus_T'.
+//
+//======================================================================
+
+PolynomialRootFinder::RootStatus_T
+Polynomial::FindRoots(double *real_zero_vector_ptr,
+ double *imaginary_zero_vector_ptr,
+ int *roots_found_ptr) const {
+ assert(m_degree >= 0);
+
+ PolynomialRootFinder *polynomial_root_finder_ptr = new PolynomialRootFinder;
+
+ if (polynomial_root_finder_ptr == NULL) {
+ throw std::bad_alloc();
+ }
+
+ std::unique_ptr root_finder_ptr(
+ polynomial_root_finder_ptr);
+
+ PolynomialRootFinder::RootStatus_T status = root_finder_ptr->FindRoots(
+ m_coefficient_vector_ptr, m_degree, real_zero_vector_ptr,
+ imaginary_zero_vector_ptr, roots_found_ptr);
+ return status;
+}
+
+//======================================================================
+// Member Function: Polynomial::IncludeRealRoot
+//
+// Abstract:
+//
+// This method multiplies this polynomial by a first order term
+// that incorporates the real root.
+//
+//
+// Input:
+//
+// real_value A real root value.
+//
+//
+// Return Value:
+//
+// The function has no return value.
+//
+//======================================================================
+
+void Polynomial::IncludeRealRoot(double real_value) {
+ if ((m_degree == 0) && (m_coefficient_vector_ptr[0] == 0.0)) {
+ SetToScalar(1.0);
+ }
+
+ double coefficient_array[2];
+ coefficient_array[0] = -real_value;
+ coefficient_array[1] = 1.0;
+ Polynomial temp_polynomial(coefficient_array, 1);
+ operator*=(temp_polynomial);
+ return;
+}
+
+//======================================================================
+// Member Function: Polynomial::IncludeComplexConjugateRootPair
+//
+// Abstract:
+//
+// This method multiplies this polynomial by a second order
+// polynomial that incorporates a complex root pair.
+//
+//
+// Input:
+//
+// real_value A real root value.
+//
+// imag_value An imaginary root value.
+//
+//
+// Return Value:
+//
+// The function has no return value.
+//
+//======================================================================
+
+void Polynomial::IncludeComplexConjugateRootPair(double real_value,
+ double imag_value) {
+ if ((m_degree == 0) && (m_coefficient_vector_ptr[0] == 0.0)) {
+ SetToScalar(1.0);
+ }
+
+ double coefficient_array[3];
+ coefficient_array[0] = real_value * real_value + imag_value * imag_value;
+ coefficient_array[1] = -(real_value + real_value);
+ coefficient_array[2] = 1.0;
+ Polynomial temp_polynomial(coefficient_array, 2);
+ operator*=(temp_polynomial);
+}
+
+//======================================================================
+// Member Function: Polynomial::Divide
+//
+// Abstract:
+//
+// This method divides this polynomial by a passed divisor
+// polynomial. The remainder polynomial is stored in the passed
+// instance remainder_polynomial.
+//
+//
+// Input:
+//
+// divisor_polynomial The divisor polynomial
+//
+// quotient_polynomial A reference to an instance of class
+// Polynomial that will contain the quotient
+// polynomial when this method returns.
+//
+// remainder_polynomial A reference to an instance of class
+// Polynomial that will contain the remainder
+// polynomial when this method returns.
+//
+// Return Value:
+//
+// This function returns a value of type 'bool' that false if this
+// method fails. This can only occur if the divisor polynomial is
+// equal to the scalar value zero. Otherwise the return value is
+// true.
+//
+//======================================================================
+
+bool Polynomial::Divide(const Polynomial &divisor_polynomial,
+ Polynomial "ient_polynomial,
+ Polynomial &remainder_polynomial) const {
+ //------------------------------------------------------------------
+ // If the divisor is zero then fail.
+ //------------------------------------------------------------------
+
+ int divisor_degree = divisor_polynomial.Degree();
+
+ bool non_zero_divisor_flag =
+ ((divisor_polynomial.Degree() != 0) || (divisor_polynomial[0] != 0.0));
+
+ if (non_zero_divisor_flag) {
+ //--------------------------------------------------------------
+ // If this dividend polynomial's degree is not greater than
+ // or equal to the divisor polynomial's degree then do the division.
+ //--------------------------------------------------------------
+
+ remainder_polynomial = *this;
+ int dividend_degree = Degree();
+ quotient_polynomial = 0.0;
+ int quotient_maximum_degree = dividend_degree - divisor_degree + 1;
+ quotient_polynomial.SetLength(quotient_maximum_degree);
+ quotient_polynomial.m_degree = -1;
+ double *quotient_coefficient_ptr =
+ quotient_polynomial.m_coefficient_vector_ptr;
+ double *dividend_coefficient_ptr =
+ remainder_polynomial.m_coefficient_vector_ptr;
+ double leading_divisor_coefficient = divisor_polynomial[divisor_degree];
+
+ //--------------------------------------------------------------
+ // Loop and subtract each scaled divisor polynomial
+ // to perform the division.
+ //--------------------------------------------------------------
+
+ int dividend_index = dividend_degree;
+
+ for (dividend_index = dividend_degree; dividend_index >= divisor_degree;
+ --dividend_index) {
+ //----------------------------------------------------------
+ // Subtract the scaled divisor from the dividend.
+ //----------------------------------------------------------
+
+ double scale_value =
+ remainder_polynomial[dividend_index] / leading_divisor_coefficient;
+
+ //----------------------------------------------------------
+ // Increase the order of the quotient polynomial.
+ //----------------------------------------------------------
+
+ quotient_polynomial.m_degree += 1;
+ int j = 0;
+
+ for (j = quotient_polynomial.m_degree; j >= 1; --j) {
+ quotient_coefficient_ptr[j] = quotient_coefficient_ptr[j - 1];
+ }
+
+ quotient_coefficient_ptr[0] = scale_value;
+
+ //----------------------------------------------------------
+ // Subtract the scaled divisor from the dividend.
+ //----------------------------------------------------------
+
+ int dividend_degree_index = dividend_index;
+
+ for (j = divisor_degree; j >= 0; --j) {
+ dividend_coefficient_ptr[dividend_degree_index] -=
+ divisor_polynomial[j] * scale_value;
+ --dividend_degree_index;
+ }
+ }
+
+ //--------------------------------------------------------------
+ // Adjust the order of the current dividend polynomial.
+ // This is the remainder polynomial.
+ //--------------------------------------------------------------
+
+ remainder_polynomial.AdjustPolynomialDegree();
+ quotient_polynomial.AdjustPolynomialDegree();
+ } else {
+ quotient_polynomial = DBL_MAX;
+ remainder_polynomial = 0.0;
+ }
+
+ return non_zero_divisor_flag;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator []
+//
+// Abstract:
+//
+// This method returns the specified polynomial coefficient.
+//
+//
+// Input:
+//
+// power_index The coefficient index.
+//
+//
+// Return Value:
+//
+// This function returns a value of type 'double' that is the
+// coefficient value corresponding to the specified power.
+//
+//======================================================================
+
+double Polynomial::operator[](int power_index) const {
+ //------------------------------------------------------------------
+ // Ensure that the index is within range.
+ //------------------------------------------------------------------
+
+ assert(m_degree >= 0);
+
+ if ((power_index < 0) || (power_index > m_degree)) {
+ throw std::exception();
+ }
+
+ return m_coefficient_vector_ptr[power_index];
+}
+
+//======================================================================
+// Member Function: Polynomial::operator []
+//
+// Abstract:
+//
+// This method returns the specified polynomial coefficient.
+//
+//
+// Input:
+//
+// power_index The coefficient index.
+//
+//
+// Return Value:
+//
+// This function returns a value of type 'double' that is the
+// coefficient value corresponding to the specified power.
+//
+//======================================================================
+
+double &Polynomial::operator[](int power_index) {
+ //------------------------------------------------------------------
+ // Ensure that the index is within range.
+ //------------------------------------------------------------------
+
+ assert(m_degree >= 0);
+
+ if ((power_index < 0) || (power_index > m_degree)) {
+ throw std::exception();
+ }
+
+ return m_coefficient_vector_ptr[power_index];
+}
+
+//======================================================================
+// Member Function: Polynomial::operator +=
+//
+// Abstract:
+//
+// This method adds a polynomial to this polynomial.
+//
+//
+// Input:
+//
+// polynomial An instance of class Polynomial
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator+=(const Polynomial &polynomial) {
+ assert(m_degree >= 0);
+
+ int i = 0;
+
+ if (m_degree >= polynomial.m_degree) {
+ for (i = 0; i <= polynomial.m_degree; ++i) {
+ m_coefficient_vector_ptr[i] += polynomial.m_coefficient_vector_ptr[i];
+ }
+ } else {
+ SetLength(polynomial.m_degree + 1, true);
+
+ for (i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] += polynomial.m_coefficient_vector_ptr[i];
+ }
+
+ for (i = m_degree + 1; i <= polynomial.m_degree; ++i) {
+ m_coefficient_vector_ptr[i] = polynomial.m_coefficient_vector_ptr[i];
+ }
+
+ m_degree = polynomial.m_degree;
+ }
+
+ //------------------------------------------------------------------
+ // If the leading coefficient(s) are zero, then decrease the
+ // polynomial degree.
+ //------------------------------------------------------------------
+
+ AdjustPolynomialDegree();
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator +=
+//
+// Abstract:
+//
+// This method adds a scalar to this polynomial.
+//
+//
+// Input:
+//
+// scalar A scalar value.
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator+=(double scalar) {
+ assert(m_degree >= 0);
+
+ m_coefficient_vector_ptr[0] += scalar;
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator -=
+//
+// Abstract:
+//
+// This method subtracts a polynomial from this polynomial.
+//
+//
+// Input:
+//
+// polynomial An instance of class Polynomial
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator-=(const Polynomial &polynomial) {
+ assert(m_degree >= 0);
+
+ int i = 0;
+
+ if (m_degree >= polynomial.m_degree) {
+ for (i = 0; i <= polynomial.m_degree; ++i) {
+ m_coefficient_vector_ptr[i] -= polynomial.m_coefficient_vector_ptr[i];
+ }
+ } else {
+ SetLength(polynomial.m_degree + 1, true);
+
+ for (i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] -= polynomial.m_coefficient_vector_ptr[i];
+ }
+
+ for (i = m_degree + 1; i <= polynomial.m_degree; ++i) {
+ m_coefficient_vector_ptr[i] = -polynomial.m_coefficient_vector_ptr[i];
+ }
+
+ m_degree = polynomial.m_degree;
+ }
+
+ //------------------------------------------------------------------
+ // If the leading coefficient(s) are zero, then decrease the
+ // polynomial degree.
+ //------------------------------------------------------------------
+
+ AdjustPolynomialDegree();
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator -=
+//
+// Abstract:
+//
+// This method subtracts a scalar from this polynomial.
+//
+//
+// Input:
+//
+// scalar A scalar value.
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator-=(double scalar) {
+ assert(m_degree >= 0);
+
+ m_coefficient_vector_ptr[0] -= scalar;
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator *=
+//
+// Abstract:
+//
+// This method multiplies a polynomial times this polynomial.
+//
+//
+// Input:
+//
+// polynomial An instance of class Polynomial
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator*=(const Polynomial &polynomial) {
+ //------------------------------------------------------------------
+ // Create a temporary buffer to hold the product of the two
+ // polynomials.
+ //------------------------------------------------------------------
+
+ assert(m_degree >= 0);
+
+ int convolution_length = m_degree + polynomial.m_degree + 1;
+
+ std::vector temp_vector;
+ temp_vector.resize(convolution_length + 1);
+ double *temp_vector_ptr = &temp_vector[0];
+
+ //------------------------------------------------------------------
+ // Zero the temporary buffer.
+ //------------------------------------------------------------------
+
+ int i = 0;
+
+ for (i = 0; i < convolution_length; ++i) {
+ temp_vector_ptr[i] = 0.0;
+ }
+
+ //------------------------------------------------------------------
+ // Calculate the convolution in the temporary buffer.
+ //------------------------------------------------------------------
+
+ for (i = 0; i <= m_degree; ++i) {
+ for (int j = 0; j <= polynomial.m_degree; ++j) {
+ temp_vector_ptr[i + j] +=
+ m_coefficient_vector_ptr[i] * polynomial.m_coefficient_vector_ptr[j];
+ }
+ }
+
+ //------------------------------------------------------------------
+ // Make sure this buffer is large enough for the product.
+ //------------------------------------------------------------------
+
+ SetLength((unsigned int)(convolution_length), false);
+
+ //------------------------------------------------------------------
+ // Store the result in this instance.
+ //------------------------------------------------------------------
+
+ m_degree = convolution_length - 1;
+
+ for (i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] = temp_vector_ptr[i];
+ }
+
+ //------------------------------------------------------------------
+ // If the leading coefficient(s) are zero, then decrease the
+ // polynomial degree.
+ //------------------------------------------------------------------
+
+ AdjustPolynomialDegree();
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator *=
+//
+// Abstract:
+//
+// This method multiplies a scalar time this polynomial.
+//
+//
+// Input:
+//
+// scalar A scalar value.
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator*=(double scalar) {
+ assert(m_degree >= 0);
+
+ int i = 0;
+
+ for (i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] *= scalar;
+ }
+
+ //------------------------------------------------------------------
+ // If the leading coefficient(s) are zero, then decrease the
+ // polynomial degree.
+ //------------------------------------------------------------------
+
+ AdjustPolynomialDegree();
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator /=
+//
+// Abstract:
+//
+// This method divides this polynomial by a scalar.
+//
+//
+// Input:
+//
+// scalar A scalar value.
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator/=(double scalar) {
+ assert(m_degree >= 0);
+
+ int i = 0;
+
+ for (i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] /= scalar;
+ }
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator +
+//
+// Abstract:
+//
+// This method implements unary operator +()
+//
+//
+// Input:
+//
+// None.
+//
+//
+// Return Value:
+//
+// This function returns a polynomial which is equal to this instance.
+//
+//======================================================================
+
+Polynomial Polynomial::operator+() {
+ assert(m_degree >= 0);
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator -
+//
+// Abstract:
+//
+// This method implements unary operator -().
+// This polynomials coefficients became the negative of
+// their present value and then this polynomial is returned.
+//
+//
+// Input:
+//
+// None.
+//
+//
+// Return Value:
+//
+// This function returns a polynomial which is the negative of
+// this instance.
+//
+//======================================================================
+
+Polynomial Polynomial::operator-() {
+ assert(m_degree >= 0);
+
+ for (int i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] = -m_coefficient_vector_ptr[i];
+ }
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator =
+//
+// Abstract:
+//
+// This method sets this polynomial to a scalar value.
+//
+//
+// Input:
+//
+// scalar A scalar value.
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator=(double scalar) {
+ SetCoefficients(&scalar, 0);
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::operator =
+//
+// Abstract:
+//
+// This method copies this polynomial.
+//
+//
+// Input:
+//
+// polynomial An instance of class Polynomial
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+Polynomial Polynomial::operator=(const Polynomial &polynomial) {
+ if (this != &polynomial) {
+ Copy(polynomial);
+ }
+
+ return *this;
+}
+
+//======================================================================
+// Member Function: Polynomial::AdjustPolynomialDegree
+//
+// Abstract:
+//
+// This method will decrease the polynomial degree until leading
+// coefficient is non-zero or until the polynomial degree is zero.
+//
+//
+// Input:
+//
+// None.
+//
+//
+// Return Value:
+//
+// This method has no return value.
+//
+//======================================================================
+
+void Polynomial::AdjustPolynomialDegree() {
+ //------------------------------------------------------------------
+ // Any leading coefficient with a magnitude less than DBL_EPSILON
+ // is treated as if it was zero.
+ //------------------------------------------------------------------
+
+ while ((m_degree > 0) &&
+ (fabs(m_coefficient_vector_ptr[m_degree]) < DBL_EPSILON)) {
+ m_coefficient_vector_ptr[m_degree] = 0.0;
+ m_degree--;
+ }
+
+ return;
+}
+
+//======================================================================
+// Member Function: Polynomial::Copy
+//
+// Abstract:
+//
+// This method copies a passed polynomial into this instance.
+//
+//
+// Input:
+//
+// polynomial An instance of class Polynomial.
+//
+//
+// Return Value:
+//
+// This function returns this polynomial.
+//
+//======================================================================
+
+void Polynomial::Copy(const Polynomial &polynomial) {
+ SetLength(polynomial.m_degree + 1);
+
+ m_degree = polynomial.m_degree;
+
+ for (int i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] = polynomial.m_coefficient_vector_ptr[i];
+ }
+
+ return;
+}
+
+//======================================================================
+// Member Function: Polynomial::SetLength
+//
+// Abstract:
+//
+// This function is called to set the buffer lengths for the
+// coefficient vector. If the new buffer length is less than
+// or equal to the current buffer lengths then then the buffer
+// is not modified and the data length is set to the new buffer
+// length. If the new data length is greater than the current
+// buffer lengths then the buffer is reallocated to the new
+// buffer size. In this case, if argument copy_data_flag
+// is set to the value true then the data in the old buffer
+// is copied to the new buffer.
+//
+//
+// Input:
+//
+// udata_length The new length of the data.
+//
+// copy_data_flag If this is true then existing data
+// is copied to any newly allocated buffer.
+// This parameter defaults to the value
+// 'true'.
+//
+// Output:
+//
+// This function has no return value.
+//
+//======================================================================
+
+void Polynomial::SetLength(unsigned int number_of_coefficients,
+ bool copy_data_flag) {
+
+ // If m_degree is equal to -1, then this is a new polynomial and the
+ // caller will set m_degree.
+ if ((!copy_data_flag) || (m_degree == -1)) {
+ // Clear and resize the coefficient vector.
+ m_coefficient_vector.clear();
+ m_coefficient_vector.resize(number_of_coefficients);
+ m_coefficient_vector_ptr = &m_coefficient_vector[0];
+ } else {
+ // Save the polynomial values in a temporary vector.
+ std::vector temp_vector;
+ temp_vector.resize(m_degree + 1);
+
+ int i = 0;
+
+ for (i = 0; i <= m_degree; ++i) {
+ temp_vector[i] = m_coefficient_vector_ptr[i];
+ }
+
+ // Clear and resize the coefficient vector.
+ m_coefficient_vector.clear();
+ m_coefficient_vector.resize(number_of_coefficients);
+ m_coefficient_vector_ptr = &m_coefficient_vector[0];
+
+ // Restore the coefficients for the new vector size.
+ // Was the polynomial size increased?
+ if (number_of_coefficients > (unsigned int)(m_degree + 1)) {
+ // The polynomial size was increased.
+ for (i = 0; i <= m_degree; ++i) {
+ m_coefficient_vector_ptr[i] = temp_vector[i];
+ }
+
+ for (i = m_degree + 1; i < (int)(number_of_coefficients); ++i) {
+ m_coefficient_vector_ptr[i] = 0.0;
+ }
+ } else {
+ for (int i = 0; i < (int)(number_of_coefficients); ++i) {
+ m_coefficient_vector_ptr[i] = temp_vector[i];
+ }
+ }
+ }
+
+ return;
+}
+
+//======================================================================
+// Global operators
+//======================================================================
+
+//======================================================================
+// Addition of two instances of this class.
+//======================================================================
+
+Polynomial operator+(const Polynomial &polynomial_0,
+ const Polynomial &polynomial_1) {
+ return Polynomial(polynomial_0) += polynomial_1;
+}
+
+//======================================================================
+// Addition of an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator+(const Polynomial &polynomial, double scalar) {
+ return Polynomial(polynomial) += scalar;
+}
+
+Polynomial operator+(double scalar, const Polynomial &polynomial) {
+ return Polynomial(polynomial) += scalar;
+}
+
+//======================================================================
+// Subtraction of two instances of this class.
+//======================================================================
+
+Polynomial operator-(const Polynomial &minuend_polynomial,
+ const Polynomial &subtrahend_polynomial) {
+ return Polynomial(minuend_polynomial) -= subtrahend_polynomial;
+}
+
+//======================================================================
+// Subtraction with an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator-(const Polynomial &minuend_polynomial, double scalar) {
+ return Polynomial(minuend_polynomial) -= scalar;
+}
+
+Polynomial operator-(double scalar, const Polynomial &polynomial) {
+ return (-Polynomial(polynomial)) + scalar;
+}
+
+//======================================================================
+// Multiplication of two instances of this class.
+//======================================================================
+
+Polynomial operator*(const Polynomial &polynomial_0,
+ const Polynomial &polynomial_1) {
+ return Polynomial(polynomial_0) *= polynomial_1;
+}
+
+//======================================================================
+// Multiplication of an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator*(const Polynomial &polynomial, double scalar) {
+ return Polynomial(polynomial) *= scalar;
+}
+
+Polynomial operator*(double scalar, const Polynomial &polynomial) {
+ return Polynomial(polynomial) *= scalar;
+}
+
+//======================================================================
+// Division with an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator/(const Polynomial &polynomial, double scalar) {
+ return Polynomial(polynomial) /= scalar;
+}
diff --git a/Polynomial.h b/Polynomial.h
new file mode 100644
index 0000000..94200c6
--- /dev/null
+++ b/Polynomial.h
@@ -0,0 +1,196 @@
+//=======================================================================
+// Copyright (C) 2003-2013 William Hallahan
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software,
+// and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//=======================================================================
+
+//**********************************************************************
+// File: Polynomial.h
+// Author: Bill Hallahan
+// Date: January 30, 2003
+//
+// Abstract:
+//
+// This file contains the definition for class Polynomial.
+//
+//**********************************************************************
+
+#ifndef POLYNOMIAL_H
+#define POLYNOMIAL_H
+
+#include "PolynomialRootFinder.h"
+#include
+
+//======================================================================
+// Class definition.
+//======================================================================
+
+class Polynomial {
+protected:
+ std::vector m_coefficient_vector;
+ int m_degree;
+ double *m_coefficient_vector_ptr;
+
+public:
+ Polynomial();
+
+ Polynomial(double scalar);
+
+ Polynomial(double x_coefficient, double scalar);
+
+ Polynomial(double x_squared_coefficient, double x_coefficient, double scalar);
+
+ Polynomial(double *coefficient_vector, int degree);
+
+ Polynomial(const Polynomial &polynomial);
+
+ virtual ~Polynomial();
+
+ void SetCoefficients(double *coefficient_vector_ptr, int degree);
+
+ void SetToScalar(double scalar);
+
+ void SetToFirstOrderPolynomial(double x_coefficient, double scalar);
+
+ void SetToQuadraticPolynomial(double x_squared_coefficient,
+ double x_coefficient, double scalar);
+
+ double EvaluateReal(double xr) const;
+
+ double EvaluateReal(double xr, double &dr) const;
+
+ void EvaluateImaginary(double xi, double &pr, double &pi) const;
+
+ void EvaluateComplex(double xr, double xi, double &pr, double &pi) const;
+
+ void EvaluateComplex(double xr, double xi, double &pr, double &pi, double &dr,
+ double &di) const;
+
+ Polynomial Derivative() const;
+
+ Polynomial Integral() const;
+
+ int Degree() const;
+
+ PolynomialRootFinder::RootStatus_T
+ FindRoots(double *real_zero_vector_ptr, double *imaginary_zero_vector_ptr,
+ int *roots_found_ptr = 0) const;
+
+ void IncludeRealRoot(double real_value);
+
+ void IncludeComplexConjugateRootPair(double real_value, double imag_value);
+
+ bool Divide(const Polynomial &divisor_polynomial,
+ Polynomial "ient_polynomial,
+ Polynomial &remainder_polynomial) const;
+
+ double operator[](int power_index) const;
+
+ double &operator[](int power_index);
+
+ Polynomial operator+=(const Polynomial &polynomial);
+
+ Polynomial operator+=(double scalar);
+
+ Polynomial operator-=(const Polynomial &polynomial);
+
+ Polynomial operator-=(double scalar);
+
+ Polynomial operator*=(const Polynomial &polynomial);
+
+ Polynomial operator*=(double scalar);
+
+ Polynomial operator/=(double scalar);
+
+ Polynomial operator+();
+
+ Polynomial operator-();
+
+ Polynomial operator=(double scalar);
+
+ Polynomial operator=(const Polynomial &polynomial);
+
+ void Copy(const Polynomial &polynomial);
+
+private:
+ void AdjustPolynomialDegree();
+
+ // void Copy(const Polynomial & polynomial);
+
+ void SetLength(unsigned int number_of_coefficients,
+ bool copy_data_flag = true);
+};
+
+//======================================================================
+// Global operators.
+//======================================================================
+
+//======================================================================
+// Addition of two instances of this class.
+//======================================================================
+
+Polynomial operator+(const Polynomial &polynomial_0,
+ const Polynomial &polynomial_1);
+
+//======================================================================
+// Addition of an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator+(const Polynomial &polynomial, double scalar);
+
+Polynomial operator+(double scalar, const Polynomial &polynomial);
+
+//======================================================================
+// Subtraction of two instances of this class.
+//======================================================================
+
+Polynomial operator-(const Polynomial &minuend_polynomial,
+ const Polynomial &subtrahend_polynomial);
+
+//======================================================================
+// Subtraction with an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator-(const Polynomial &minuend_polynomial, double scalar);
+
+Polynomial operator-(double scalar, const Polynomial &polynomial);
+
+//======================================================================
+// Multiplication of two instances of this class.
+//======================================================================
+
+Polynomial operator*(const Polynomial &polynomial_0,
+ const Polynomial &polynomial_1);
+
+//======================================================================
+// Multiplication of an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator*(const Polynomial &polynomial, double scalar);
+
+Polynomial operator*(double scalar, const Polynomial &polynomial);
+
+//======================================================================
+// Division with an instance of the Polynomial class and a scalar.
+//======================================================================
+
+Polynomial operator/(const Polynomial &polynomial, double scalar);
+#endif
diff --git a/PolynomialRootFinder.cpp b/PolynomialRootFinder.cpp
new file mode 100644
index 0000000..28fabb0
--- /dev/null
+++ b/PolynomialRootFinder.cpp
@@ -0,0 +1,1362 @@
+//=======================================================================
+// Copyright (C) 2003-2013 William Hallahan
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software,
+// and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//=======================================================================
+
+//**********************************************************************
+// File: PolynomialRootFinder.cpp
+// Author: Bill Hallahan
+// Date: January 30, 2003
+//
+// Abstract:
+//
+// This file contains the implementation for class
+// PolynomialRootFinder.
+//
+//**********************************************************************
+
+#include "PolynomialRootFinder.h"
+#include
+#include
+
+//======================================================================
+// Local constants.
+//======================================================================
+
+namespace {
+//------------------------------------------------------------------
+// The following machine constants are used in this method.
+//
+// f_BASE The base of the floating point number system used.
+//
+// f_ETA The maximum relative representation error which
+// can be described as the smallest positive floating
+// point number such that 1.0 + f_ETA is greater than 1.0.
+//
+// f_MAXIMUM_FLOAT The largest floating point number.
+//
+// f_MINIMUM_FLOAT The smallest positive floating point number.
+//
+//------------------------------------------------------------------
+
+const float f_BASE = 2.0;
+const float f_ETA = FLT_EPSILON;
+const float f_ETA_N = (float)(10.0) * f_ETA;
+const float f_ETA_N_SQUARED = (float)(100.0) * f_ETA;
+const float f_MAXIMUM_FLOAT = FLT_MAX;
+const float f_MINIMUM_FLOAT = FLT_MIN;
+const float f_XX_INITIAL_VALUE = (float)(0.70710678);
+const float f_COSR_INITIAL_VALUE = (float)(-0.069756474);
+const float f_SINR_INITIAL_VALUE = (float)(0.99756405);
+}; // namespace
+
+//======================================================================
+// Constructor: PolynomialRootFinder::PolynomialRootFinder
+//======================================================================
+
+PolynomialRootFinder::PolynomialRootFinder() {}
+
+//======================================================================
+// Destructor: PolynomialRootFinder::~PolynomialRootFinder
+//======================================================================
+
+PolynomialRootFinder::~PolynomialRootFinder() {}
+
+//======================================================================
+// Member Function: PolynomialRootFinder::FindRoots
+//
+// Abstract:
+//
+// This method determines the roots of a polynomial which
+// has real coefficients. This code is based on FORTRAN
+// code published in reference [1]. The method is based on
+// an algorithm the three-stage algorithm described in
+// Jenkins and Traub [2].
+//
+// 1. "Collected Algorithms from ACM, Volume III", Algorithms 493-545
+// 1983. (The root finding algorithms is number 493)
+//
+// 2. Jenkins, M. A. and Traub, J. F., "A three-stage algorithm for
+// real polynomials using quadratic iteration", SIAM Journal of
+// Numerical Analysis, 7 (1970), 545-566
+//
+// 3. Jenkins, M. A. and Traub, J. F., "Principles for testing
+// polynomial zerofinding programs", ACM TOMS 1,
+// 1 (March 1975), 26-34
+//
+//
+// Input:
+//
+// All vectors below must be at least a length equal to degree + 1.
+//
+// coefficicent_ptr A double precision vector that contains
+// the polynomial coefficients in order
+// of increasing power.
+//
+// degree The degree of the polynomial.
+//
+// real_zero_vector_ptr A double precision vector that will
+// contain the real parts of the roots
+// of the polynomial when this method
+// returns.
+//
+// imaginary_zero_vector_ptr A double precision vector that will
+// contain the real parts of the roots
+// of the polynomial when this method
+// returns.
+//
+// number_of_roots_found_ptr A pointer to an integer that will
+// equal the number of roots found when
+// this method returns. If the method
+// returns SUCCESS then this value will
+// always equal the degree of the
+// polynomial.
+//
+// Return Value:
+//
+// The function returns an enum value of type
+// 'PolynomialRootFinder::RootStatus_T'.
+//
+//======================================================================
+
+PolynomialRootFinder::RootStatus_T PolynomialRootFinder::FindRoots(
+ double *coefficient_vector_ptr, int degree, double *real_zero_vector_ptr,
+ double *imaginary_zero_vector_ptr, int *number_of_roots_found_ptr) {
+ //--------------------------------------------------------------
+ // The algorithm fails if the polynomial is not at least
+ // degree on or the leading coefficient is zero.
+ //--------------------------------------------------------------
+
+ PolynomialRootFinder::RootStatus_T status;
+
+ if (degree == 0) {
+ status = PolynomialRootFinder::SCALAR_VALUE_HAS_NO_ROOTS;
+ } else if (coefficient_vector_ptr[degree] == 0.0) {
+ status = PolynomialRootFinder::LEADING_COEFFICIENT_IS_ZERO;
+ } else {
+ //--------------------------------------------------------------
+ // Allocate temporary vectors used to find the roots.
+ //--------------------------------------------------------------
+
+ m_degree = degree;
+
+ std::vector temp_vector;
+ std::vector pt_vector;
+
+ m_p_vector.resize(m_degree + 1);
+ m_qp_vector.resize(m_degree + 1);
+ m_k_vector.resize(m_degree + 1);
+ m_qk_vector.resize(m_degree + 1);
+ m_svk_vector.resize(m_degree + 1);
+ temp_vector.resize(m_degree + 1);
+ pt_vector.resize(m_degree + 1);
+
+ m_p_vector_ptr = &m_p_vector[0];
+ m_qp_vector_ptr = &m_qp_vector[0];
+ m_k_vector_ptr = &m_k_vector[0];
+ m_qk_vector_ptr = &m_qk_vector[0];
+ m_svk_vector_ptr = &m_svk_vector[0];
+ double *temp_vector_ptr = &temp_vector[0];
+ PRF_Float_T *pt_vector_ptr = &pt_vector[0];
+
+ //--------------------------------------------------------------
+ // m_are and m_mre refer to the unit error in + and *
+ // respectively. they are assumed to be the same as
+ // f_ETA.
+ //--------------------------------------------------------------
+
+ m_are = f_ETA;
+ m_mre = f_ETA;
+ PRF_Float_T lo = f_MINIMUM_FLOAT / f_ETA;
+
+ //--------------------------------------------------------------
+ // Initialization of constants for shift rotation.
+ //--------------------------------------------------------------
+
+ PRF_Float_T xx = f_XX_INITIAL_VALUE;
+ PRF_Float_T yy = -xx;
+ PRF_Float_T cosr = f_COSR_INITIAL_VALUE;
+ PRF_Float_T sinr = f_SINR_INITIAL_VALUE;
+ m_n = m_degree;
+ m_n_plus_one = m_n + 1;
+
+ //--------------------------------------------------------------
+ // Make a copy of the coefficients in reverse order.
+ //--------------------------------------------------------------
+
+ int ii = 0;
+
+ for (ii = 0; ii < m_n_plus_one; ++ii) {
+ m_p_vector_ptr[m_n - ii] = coefficient_vector_ptr[ii];
+ }
+
+ //--------------------------------------------------------------
+ // Assume failure. The status is set to SUCCESS if all
+ // the roots are found.
+ //--------------------------------------------------------------
+
+ status = PolynomialRootFinder::FAILED_TO_CONVERGE;
+
+ //--------------------------------------------------------------
+ // If there are any zeros at the origin, remove them.
+ //--------------------------------------------------------------
+
+ int jvar = 0;
+
+ while (m_p_vector_ptr[m_n] == 0.0) {
+ jvar = m_degree - m_n;
+ real_zero_vector_ptr[jvar] = 0.0;
+ imaginary_zero_vector_ptr[jvar] = 0.0;
+ m_n_plus_one = m_n_plus_one - 1;
+ m_n = m_n - 1;
+ }
+
+ //--------------------------------------------------------------
+ // Loop and find polynomial zeros. In the original algorithm
+ // this loop was an infinite loop. Testing revealed that the
+ // number of main loop iterations to solve a polynomial of a
+ // particular degree is usually about half the degree.
+ // We loop twice that to make sure the solution is found.
+ // (This should be revisited as it might preclude solving
+ // some large polynomials.)
+ //--------------------------------------------------------------
+
+ int count = 0;
+
+ for (count = 0; count < m_degree; ++count) {
+ //----------------------------------------------------------
+ // Check for less than 2 zeros to finish the solution.
+ //----------------------------------------------------------
+
+ if (m_n <= 2) {
+ if (m_n > 0) {
+ //--------------------------------------------------
+ // Calculate the final zero or pair of zeros.
+ //--------------------------------------------------
+
+ if (m_n == 1) {
+ real_zero_vector_ptr[m_degree - 1] =
+ -m_p_vector_ptr[1] / m_p_vector_ptr[0];
+
+ imaginary_zero_vector_ptr[m_degree - 1] = 0.0;
+ } else {
+ SolveQuadraticEquation(m_p_vector_ptr[0], m_p_vector_ptr[1],
+ m_p_vector_ptr[2],
+ real_zero_vector_ptr[m_degree - 2],
+ imaginary_zero_vector_ptr[m_degree - 2],
+ real_zero_vector_ptr[m_degree - 1],
+ imaginary_zero_vector_ptr[m_degree - 1]);
+ }
+ }
+
+ m_n = 0;
+ status = PolynomialRootFinder::SUCCESS;
+ break;
+ } else {
+ //------------------------------------------------------
+ // Find largest and smallest moduli of coefficients.
+ //------------------------------------------------------
+
+ PRF_Float_T max = 0.0;
+ PRF_Float_T min = f_MAXIMUM_FLOAT;
+ PRF_Float_T xvar;
+
+ for (ii = 0; ii < m_n_plus_one; ++ii) {
+ xvar = (PRF_Float_T)(::fabs((PRF_Float_T)(m_p_vector_ptr[ii])));
+
+ if (xvar > max) {
+ max = xvar;
+ }
+
+ if ((xvar != 0.0) && (xvar < min)) {
+ min = xvar;
+ }
+ }
+
+ //------------------------------------------------------
+ // Scale if there are large or very small coefficients.
+ // Computes a scale factor to multiply the coefficients
+ // of the polynomial. The scaling is done to avoid
+ // overflow and to avoid undetected underflow from
+ // interfering with the convergence criterion.
+ // The factor is a power of the base.
+ //------------------------------------------------------
+
+ bool do_scaling_flag = false;
+ PRF_Float_T sc = lo / min;
+
+ if (sc <= 1.0) {
+ do_scaling_flag = f_MAXIMUM_FLOAT / sc < max;
+ } else {
+ do_scaling_flag = max < 10.0;
+
+ if (!do_scaling_flag) {
+ if (sc == 0.0) {
+ sc = f_MINIMUM_FLOAT;
+ }
+ }
+ }
+
+ //------------------------------------------------------
+ // Conditionally scale the data.
+ //------------------------------------------------------
+
+ if (do_scaling_flag) {
+ int lvar = (int)(::log(sc) / ::log(f_BASE) + 0.5);
+ double factor = ::pow((double)(f_BASE * 1.0), double(lvar));
+
+ if (factor != 1.0) {
+ for (ii = 0; ii < m_n_plus_one; ++ii) {
+ m_p_vector_ptr[ii] = factor * m_p_vector_ptr[ii];
+ }
+ }
+ }
+
+ //------------------------------------------------------
+ // Compute lower bound on moduli of zeros.
+ //------------------------------------------------------
+
+ for (ii = 0; ii < m_n_plus_one; ++ii) {
+ pt_vector_ptr[ii] =
+ (PRF_Float_T)(::fabs((PRF_Float_T)(m_p_vector_ptr[ii])));
+ }
+
+ pt_vector_ptr[m_n] = -pt_vector_ptr[m_n];
+
+ //------------------------------------------------------
+ // Compute upper estimate of bound.
+ //------------------------------------------------------
+
+ xvar = (PRF_Float_T)(
+ ::exp((::log(-pt_vector_ptr[m_n]) - ::log(pt_vector_ptr[0])) /
+ (PRF_Float_T)(m_n)));
+
+ //------------------------------------------------------
+ // If newton step at the origin is better, use it.
+ //------------------------------------------------------
+
+ PRF_Float_T xm;
+
+ if (pt_vector_ptr[m_n - 1] != 0.0) {
+ xm = -pt_vector_ptr[m_n] / pt_vector_ptr[m_n - 1];
+
+ if (xm < xvar) {
+ xvar = xm;
+ }
+ }
+
+ //------------------------------------------------------
+ // Chop the interval (0, xvar) until ff <= 0
+ //------------------------------------------------------
+
+ PRF_Float_T ff;
+
+ while (true) {
+ xm = (PRF_Float_T)(xvar * 0.1);
+ ff = pt_vector_ptr[0];
+
+ for (ii = 1; ii < m_n_plus_one; ++ii) {
+ ff = ff * xm + pt_vector_ptr[ii];
+ }
+
+ if (ff <= 0.0) {
+ break;
+ }
+
+ xvar = xm;
+ }
+
+ PRF_Float_T dx = xvar;
+
+ //------------------------------------------------------
+ // Do newton iteration until xvar converges to two
+ // decimal places.
+ //------------------------------------------------------
+
+ while (true) {
+ if ((PRF_Float_T)(::fabs(dx / xvar)) <= 0.005) {
+ break;
+ }
+
+ ff = pt_vector_ptr[0];
+ PRF_Float_T df = ff;
+
+ for (ii = 1; ii < m_n; ++ii) {
+ ff = ff * xvar + pt_vector_ptr[ii];
+ df = df * xvar + ff;
+ }
+
+ ff = ff * xvar + pt_vector_ptr[m_n];
+ dx = ff / df;
+ xvar = xvar - dx;
+ }
+
+ PRF_Float_T bnd = xvar;
+
+ //------------------------------------------------------
+ // Compute the derivative as the intial m_k_vector_ptr
+ // polynomial and do 5 steps with no shift.
+ //------------------------------------------------------
+
+ int n_minus_one = m_n - 1;
+
+ for (ii = 1; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] =
+ (PRF_Float_T)(m_n - ii) * m_p_vector_ptr[ii] / (PRF_Float_T)(m_n);
+ }
+
+ m_k_vector_ptr[0] = m_p_vector_ptr[0];
+ double aa = m_p_vector_ptr[m_n];
+ double bb = m_p_vector_ptr[m_n - 1];
+ bool zerok_flag = m_k_vector_ptr[m_n - 1] == 0.0;
+
+ int jj = 0;
+
+ for (jj = 1; jj <= 5; ++jj) {
+ double cc = m_k_vector_ptr[m_n - 1];
+
+ if (zerok_flag) {
+ //----------------------------------------------
+ // Use unscaled form of recurrence.
+ //----------------------------------------------
+
+ for (jvar = n_minus_one; jvar > 0; --jvar) {
+ m_k_vector_ptr[jvar] = m_k_vector_ptr[jvar - 1];
+ }
+
+ m_k_vector_ptr[0] = 0.0;
+ zerok_flag = m_k_vector_ptr[m_n - 1] == 0.0;
+ } else {
+ //----------------------------------------------
+ // Use scaled form of recurrence if value
+ // of m_k_vector_ptr at 0 is nonzero.
+ //----------------------------------------------
+
+ double tvar = -aa / cc;
+
+ for (jvar = n_minus_one; jvar > 0; --jvar) {
+ m_k_vector_ptr[jvar] =
+ tvar * m_k_vector_ptr[jvar - 1] + m_p_vector_ptr[jvar];
+ }
+
+ m_k_vector_ptr[0] = m_p_vector_ptr[0];
+ zerok_flag =
+ ::fabs(m_k_vector_ptr[m_n - 1]) <= ::fabs(bb) * f_ETA_N;
+ }
+ }
+
+ //------------------------------------------------------
+ // Save m_k_vector_ptr for restarts with new shifts.
+ //------------------------------------------------------
+
+ for (ii = 0; ii < m_n; ++ii) {
+ temp_vector_ptr[ii] = m_k_vector_ptr[ii];
+ }
+
+ //------------------------------------------------------
+ // Loop to select the quadratic corresponding to
+ // each new shift.
+ //------------------------------------------------------
+
+ int cnt = 0;
+
+ for (cnt = 1; cnt <= 20; ++cnt) {
+ //--------------------------------------------------
+ // Quadratic corresponds to a double shift to a
+ // non-real point and its complex conjugate. The
+ // point has modulus 'bnd' and amplitude rotated
+ // by 94 degrees from the previous shift.
+ //--------------------------------------------------
+
+ PRF_Float_T xxx = cosr * xx - sinr * yy;
+ yy = sinr * xx + cosr * yy;
+ xx = xxx;
+ m_real_s = bnd * xx;
+ m_imag_s = bnd * yy;
+ m_u = -2.0 * m_real_s;
+ m_v = bnd;
+
+ //--------------------------------------------------
+ // Second stage calculation, fixed quadratic.
+ // Variable nz will contain the number of
+ // zeros found when function Fxshfr() returns.
+ //--------------------------------------------------
+
+ int nz = Fxshfr(20 * cnt);
+
+ if (nz != 0) {
+ //----------------------------------------------
+ // The second stage jumps directly to one of
+ // the third stage iterations and returns here
+ // if successful. Deflate the polynomial,
+ // store the zero or zeros and return to the
+ // main algorithm.
+ //----------------------------------------------
+
+ jvar = m_degree - m_n;
+ real_zero_vector_ptr[jvar] = m_real_sz;
+ imaginary_zero_vector_ptr[jvar] = m_imag_sz;
+ m_n_plus_one = m_n_plus_one - nz;
+ m_n = m_n_plus_one - 1;
+
+ for (ii = 0; ii < m_n_plus_one; ++ii) {
+ m_p_vector_ptr[ii] = m_qp_vector_ptr[ii];
+ }
+
+ if (nz != 1) {
+ real_zero_vector_ptr[jvar + 1] = m_real_lz;
+ imaginary_zero_vector_ptr[jvar + 1] = m_imag_lz;
+ }
+
+ break;
+
+ //----------------------------------------------
+ // If the iteration is unsuccessful another
+ // quadratic is chosen after restoring
+ // m_k_vector_ptr.
+ //----------------------------------------------
+ }
+
+ for (ii = 0; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] = temp_vector_ptr[ii];
+ }
+ }
+ }
+ }
+
+ //--------------------------------------------------------------
+ // If no convergence with 20 shifts then adjust the degree
+ // for the number of roots found.
+ //--------------------------------------------------------------
+
+ if (number_of_roots_found_ptr != 0) {
+ *number_of_roots_found_ptr = m_degree - m_n;
+ }
+ }
+
+ return status;
+}
+
+//======================================================================
+// Computes up to l2var fixed shift m_k_vector_ptr polynomials,
+// testing for convergence in the linear or quadratic
+// case. initiates one of the variable shift
+// iterations and returns with the number of zeros
+// found.
+//
+// l2var An integer that is the limit of fixed shift steps.
+//
+// Return Value:
+// nz An integer that is the number of zeros found.
+//======================================================================
+
+int PolynomialRootFinder::Fxshfr(int l2var) {
+ //------------------------------------------------------------------
+ // Evaluate polynomial by synthetic division.
+ //------------------------------------------------------------------
+
+ QuadraticSyntheticDivision(m_n_plus_one, m_u, m_v, m_p_vector_ptr,
+ m_qp_vector_ptr, m_a, m_b);
+
+ int itype = CalcSc();
+
+ int nz = 0;
+ float betav = 0.25;
+ float betas = 0.25;
+ float oss = (float)(m_real_s);
+ float ovv = (float)(m_v);
+ float ots;
+ float otv;
+ double ui;
+ double vi;
+ double svar;
+
+ int jvar = 0;
+
+ for (jvar = 1; jvar <= l2var; ++jvar) {
+ //--------------------------------------------------------------
+ // Calculate next m_k_vector_ptr polynomial and estimate m_v.
+ //--------------------------------------------------------------
+
+ NextK(itype);
+ itype = CalcSc();
+ Newest(itype, ui, vi);
+ float vv = (float)(vi);
+
+ //--------------------------------------------------------------
+ // Estimate svar
+ //--------------------------------------------------------------
+
+ float ss = 0.0;
+
+ if (m_k_vector_ptr[m_n - 1] != 0.0) {
+ ss = (float)(-m_p_vector_ptr[m_n] / m_k_vector_ptr[m_n - 1]);
+ }
+
+ float tv = 1.0;
+ float ts = 1.0;
+
+ if ((jvar != 1) && (itype != 3)) {
+ //----------------------------------------------------------
+ // Compute relative measures of convergence of
+ // svar and m_v sequences.
+ //----------------------------------------------------------
+
+ if (vv != 0.0) {
+ tv = (float)(::fabs((vv - ovv) / vv));
+ }
+
+ if (ss != 0.0) {
+ ts = (float)(::fabs((ss - oss) / ss));
+ }
+
+ //----------------------------------------------------------
+ // If decreasing, multiply two most recent convergence
+ // measures.
+ //----------------------------------------------------------
+
+ float tvv = 1.0;
+
+ if (tv < otv) {
+ tvv = tv * otv;
+ }
+
+ float tss = 1.0;
+
+ if (ts < ots) {
+ tss = ts * ots;
+ }
+
+ //----------------------------------------------------------
+ // Compare with convergence criteria.
+ //----------------------------------------------------------
+
+ bool vpass_flag = tvv < betav;
+ bool spass_flag = tss < betas;
+
+ if (spass_flag || vpass_flag) {
+ //------------------------------------------------------
+ // At least one sequence has passed the convergence
+ // test. Store variables before iterating.
+ //------------------------------------------------------
+
+ double svu = m_u;
+ double svv = m_v;
+ int ii = 0;
+
+ for (ii = 0; ii < m_n; ++ii) {
+ m_svk_vector_ptr[ii] = m_k_vector_ptr[ii];
+ }
+
+ svar = ss;
+
+ //------------------------------------------------------
+ // Choose iteration according to the fastest
+ // converging sequence.
+ //------------------------------------------------------
+
+ bool vtry_flag = false;
+ bool stry_flag = false;
+ bool exit_outer_loop_flag = false;
+
+ bool start_with_real_iteration_flag =
+ (spass_flag && ((!vpass_flag) || (tss < tvv)));
+
+ do {
+ if (!start_with_real_iteration_flag) {
+ nz = QuadraticIteration(ui, vi);
+
+ if (nz > 0) {
+ exit_outer_loop_flag = true;
+ break;
+ }
+
+ //----------------------------------------------
+ // Quadratic iteration has failed. flag
+ // that it has been tried and decrease
+ // the convergence criterion.
+ //----------------------------------------------
+
+ vtry_flag = true;
+ betav = (float)(betav * 0.25);
+ }
+
+ //--------------------------------------------------
+ // Try linear iteration if it has not been
+ // tried and the svar sequence is converging.
+ //--------------------------------------------------
+
+ if (((!stry_flag) && spass_flag) || start_with_real_iteration_flag) {
+ if (!start_with_real_iteration_flag) {
+ for (ii = 0; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] = m_svk_vector_ptr[ii];
+ }
+ } else {
+ start_with_real_iteration_flag = false;
+ }
+
+ int iflag = 0;
+
+ nz = RealIteration(svar, iflag);
+
+ if (nz > 0) {
+ exit_outer_loop_flag = true;
+ break;
+ }
+
+ //----------------------------------------------
+ // Linear iteration has failed. Flag that
+ // it has been tried and decrease the
+ // convergence criterion.
+ //----------------------------------------------
+
+ stry_flag = true;
+ betas = (float)(betas * 0.25);
+
+ if (iflag != 0) {
+ //------------------------------------------
+ // If linear iteration signals an almost
+ // double real zero attempt quadratic
+ // iteration.
+ //------------------------------------------
+
+ ui = -(svar + svar);
+ vi = svar * svar;
+
+ continue;
+ }
+ }
+
+ //--------------------------------------------------
+ // Restore variables
+ //--------------------------------------------------
+
+ m_u = svu;
+ m_v = svv;
+
+ for (ii = 0; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] = m_svk_vector_ptr[ii];
+ }
+
+ //----------------------------------------------
+ // Try quadratic iteration if it has not been
+ // tried and the m_v sequence is converging.
+ //----------------------------------------------
+ } while (vpass_flag && (!vtry_flag));
+
+ if (exit_outer_loop_flag) {
+ break;
+ }
+
+ //------------------------------------------------------
+ // Recompute m_qp_vector_ptr and scalar values to
+ // continue the second stage.
+ //------------------------------------------------------
+
+ QuadraticSyntheticDivision(m_n_plus_one, m_u, m_v, m_p_vector_ptr,
+ m_qp_vector_ptr, m_a, m_b);
+
+ itype = CalcSc();
+ }
+ }
+
+ ovv = vv;
+ oss = ss;
+ otv = tv;
+ ots = ts;
+ }
+
+ return nz;
+}
+
+//======================================================================
+// Variable-shift m_k_vector_ptr-polynomial iteration for
+// a quadratic factor converges only if the zeros are
+// equimodular or nearly so.
+//
+// uu Coefficients of starting quadratic
+// vv Coefficients of starting quadratic
+//
+// Return value:
+// nz The number of zeros found.
+//======================================================================
+
+int PolynomialRootFinder::QuadraticIteration(double uu, double vv) {
+ //------------------------------------------------------------------
+ // Main loop
+ //------------------------------------------------------------------
+
+ double ui = 0.0;
+ double vi = 0.0;
+ float omp = 0.0F;
+ float relstp = 0.0F;
+ int itype = 0;
+ bool tried_flag = false;
+ int jvar = 0;
+ int nz = 0;
+ m_u = uu;
+ m_v = vv;
+
+ while (true) {
+ SolveQuadraticEquation(1.0, m_u, m_v, m_real_sz, m_imag_sz, m_real_lz,
+ m_imag_lz);
+
+ //--------------------------------------------------------------
+ // Return if roots of the quadratic are real and not close
+ // to multiple or nearly equal and of opposite sign.
+ //--------------------------------------------------------------
+
+ if (::fabs(::fabs(m_real_sz) - ::fabs(m_real_lz)) >
+ 0.01 * ::fabs(m_real_lz)) {
+ break;
+ }
+
+ //--------------------------------------------------------------
+ // Evaluate polynomial by quadratic synthetic division.
+ //------------------------------------------------------------------
+
+ QuadraticSyntheticDivision(m_n_plus_one, m_u, m_v, m_p_vector_ptr,
+ m_qp_vector_ptr, m_a, m_b);
+
+ float mp = (float)(::fabs(m_a - m_real_sz * m_b) + ::fabs(m_imag_sz * m_b));
+
+ //--------------------------------------------------------------
+ // Compute a rigorous bound on the rounding error in
+ // evaluting m_p_vector_ptr.
+ //--------------------------------------------------------------
+
+ float zm = (float)(::sqrt((float)(::fabs((float)(m_v)))));
+ float ee = (float)(2.0 * (float)(::fabs((float)(m_qp_vector_ptr[0]))));
+ float tvar = (float)(-m_real_sz * m_b);
+ int ii = 0;
+
+ for (ii = 1; ii < m_n; ++ii) {
+ ee = ee * zm + (float)(::fabs((float)(m_qp_vector_ptr[ii])));
+ }
+
+ ee = ee * zm + (float)(::fabs((float)(m_a) + tvar));
+ ee = (float)((5.0 * m_mre + 4.0 * m_are) * ee -
+ (5.0 * m_mre + 2.0 * m_are) *
+ ((float)(::fabs((float)(m_a) + tvar)) +
+ (float)(::fabs((float)(m_b))) * zm) +
+ 2.0 * m_are * (float)(::fabs(tvar)));
+
+ //--------------------------------------------------------------
+ // Iteration has converged sufficiently if the polynomial
+ // value is less than 20 times this bound.
+ //--------------------------------------------------------------
+
+ if (mp <= 20.0 * ee) {
+ nz = 2;
+ break;
+ }
+
+ jvar = jvar + 1;
+
+ //--------------------------------------------------------------
+ // Stop iteration after 20 steps.
+ //--------------------------------------------------------------
+
+ if (jvar > 20) {
+ break;
+ }
+
+ if ((jvar >= 2) && ((relstp <= 0.01) && (mp >= omp) && (!tried_flag))) {
+ //----------------------------------------------------------
+ // A cluster appears to be stalling the convergence.
+ // Five fixed shift steps are taken with a m_u, m_v
+ // close to the cluster.
+ //----------------------------------------------------------
+
+ if (relstp < f_ETA) {
+ relstp = f_ETA;
+ }
+
+ relstp = (float)(::sqrt(relstp));
+ m_u = m_u - m_u * relstp;
+ m_v = m_v + m_v * relstp;
+
+ QuadraticSyntheticDivision(m_n_plus_one, m_u, m_v, m_p_vector_ptr,
+ m_qp_vector_ptr, m_a, m_b);
+
+ for (ii = 0; ii < 5; ++ii) {
+ itype = CalcSc();
+ NextK(itype);
+ }
+
+ tried_flag = true;
+ jvar = 0;
+ }
+
+ omp = mp;
+
+ //--------------------------------------------------------------
+ // Calculate next m_k_vector_ptr polynomial and
+ // new m_u and m_v.
+ //--------------------------------------------------------------
+
+ itype = CalcSc();
+ NextK(itype);
+ itype = CalcSc();
+ Newest(itype, ui, vi);
+
+ //--------------------------------------------------------------
+ // If vi is zero the iteration is not converging.
+ //--------------------------------------------------------------
+
+ if (vi == 0.0) {
+ break;
+ }
+
+ relstp = (float)(::fabs((vi - m_v) / vi));
+ m_u = ui;
+ m_v = vi;
+ }
+
+ return nz;
+}
+
+//======================================================================
+// Variable-shift h polynomial iteration for a real zero.
+//
+// sss Starting iterate
+// flag Flag to indicate a pair of zeros near real axis.
+//
+// Return Value:
+// Number of zero found.
+//======================================================================
+
+int PolynomialRootFinder::RealIteration(double &sss, int &flag) {
+ //------------------------------------------------------------------
+ // Main loop
+ //------------------------------------------------------------------
+
+ double tvar = 0.0;
+ float omp = 0.0F;
+ int nz = 0;
+ flag = 0;
+ int jvar = 0;
+ double svar = sss;
+
+ while (true) {
+ double pv = m_p_vector_ptr[0];
+
+ //--------------------------------------------------------------
+ // Evaluate m_p_vector_ptr at svar
+ //--------------------------------------------------------------
+
+ m_qp_vector_ptr[0] = pv;
+ int ii = 0;
+
+ for (ii = 1; ii < m_n_plus_one; ++ii) {
+ pv = pv * svar + m_p_vector_ptr[ii];
+ m_qp_vector_ptr[ii] = pv;
+ }
+
+ float mp = (float)(::fabs(pv));
+
+ //--------------------------------------------------------------
+ // Compute a rigorous bound on the error in evaluating p
+ //--------------------------------------------------------------
+
+ PRF_Float_T ms = (PRF_Float_T)(::fabs(svar));
+ PRF_Float_T ee = (m_mre / (m_are + m_mre)) *
+ (PRF_Float_T)(::fabs((PRF_Float_T)(m_qp_vector_ptr[0])));
+
+ for (ii = 1; ii < m_n_plus_one; ++ii) {
+ ee = ee * ms + (float)(::fabs((PRF_Float_T)(m_qp_vector_ptr[ii])));
+ }
+
+ //--------------------------------------------------------------
+ // Iteration has converged sufficiently if the
+ // polynomial value is less than 20 times this bound.
+ //--------------------------------------------------------------
+
+ if (mp <= 20.0 * ((m_are + m_mre) * ee - m_mre * mp)) {
+ nz = 1;
+ m_real_sz = svar;
+ m_imag_sz = 0.0;
+ break;
+ }
+
+ jvar = jvar + 1;
+
+ //--------------------------------------------------------------
+ // Stop iteration after 10 steps.
+ //--------------------------------------------------------------
+
+ if (jvar > 10) {
+ break;
+ }
+
+ if ((jvar >= 2) &&
+ ((::fabs(tvar) <= 0.001 * ::fabs(svar - tvar)) && (mp > omp))) {
+ //----------------------------------------------------------
+ // A cluster of zeros near the real axis has been
+ // encountered. Return with flag set to initiate
+ // a quadratic iteration.
+ //----------------------------------------------------------
+
+ flag = 1;
+ sss = svar;
+ break;
+ }
+
+ //--------------------------------------------------------------
+ // Return if the polynomial value has increased significantly.
+ //--------------------------------------------------------------
+
+ omp = mp;
+
+ //--------------------------------------------------------------
+ // Compute t, the next polynomial, and the new iterate.
+ //--------------------------------------------------------------
+
+ double kv = m_k_vector_ptr[0];
+ m_qk_vector_ptr[0] = kv;
+
+ for (ii = 1; ii < m_n; ++ii) {
+ kv = kv * svar + m_k_vector_ptr[ii];
+ m_qk_vector_ptr[ii] = kv;
+ }
+
+ if (::fabs(kv) <= ::fabs(m_k_vector_ptr[m_n - 1]) * f_ETA_N) {
+ m_k_vector_ptr[0] = 0.0;
+
+ for (ii = 1; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] = m_qk_vector_ptr[ii - 1];
+ }
+ } else {
+ //----------------------------------------------------------
+ // Use the scaled form of the recurrence if the
+ // value of m_k_vector_ptr at svar is non-zero.
+ //----------------------------------------------------------
+
+ tvar = -pv / kv;
+ m_k_vector_ptr[0] = m_qp_vector_ptr[0];
+
+ for (ii = 1; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] =
+ tvar * m_qk_vector_ptr[ii - 1] + m_qp_vector_ptr[ii];
+ }
+ }
+
+ //--------------------------------------------------------------
+ // Use unscaled form.
+ //--------------------------------------------------------------
+
+ kv = m_k_vector_ptr[0];
+
+ for (ii = 1; ii < m_n; ++ii) {
+ kv = kv * svar + m_k_vector_ptr[ii];
+ }
+
+ tvar = 0.0;
+
+ if (::fabs(kv) > ::fabs(m_k_vector_ptr[m_n - 1]) * f_ETA_N) {
+ tvar = -pv / kv;
+ }
+
+ svar = svar + tvar;
+ }
+
+ return nz;
+}
+
+//======================================================================
+// This routine calculates scalar quantities used to compute
+// the next m_k_vector_ptr polynomial and new estimates of the
+// quadratic coefficients.
+//
+// Return Value:
+// type Integer variable set here indicating how the
+// calculations are normalized to avoid overflow.
+//======================================================================
+
+int PolynomialRootFinder::CalcSc() {
+ //------------------------------------------------------------------
+ // Synthetic division of m_k_vector_ptr by the quadratic 1, m_u, m_v.
+ //------------------------------------------------------------------
+
+ QuadraticSyntheticDivision(m_n, m_u, m_v, m_k_vector_ptr, m_qk_vector_ptr,
+ m_c, m_d);
+
+ int itype = 0;
+
+ if ((::fabs(m_c) <= ::fabs(m_k_vector_ptr[m_n - 1]) * f_ETA_N_SQUARED) &&
+ (::fabs(m_d) <= ::fabs(m_k_vector_ptr[m_n - 2]) * f_ETA_N_SQUARED)) {
+ //--------------------------------------------------------------
+ // itype == 3 Indicates the quadratic is almost a
+ // factor of m_k_vector_ptr.
+ //--------------------------------------------------------------
+
+ itype = 3;
+ } else if (::fabs(m_d) >= ::fabs(m_c)) {
+ //--------------------------------------------------------------
+ // itype == 2 Indicates that all formulas are divided by m_d.
+ //--------------------------------------------------------------
+
+ itype = 2;
+ m_e = m_a / m_d;
+ m_f = m_c / m_d;
+ m_g = m_u * m_b;
+ m_h = m_v * m_b;
+ m_a3 = (m_a + m_g) * m_e + m_h * (m_b / m_d);
+ m_a1 = m_b * m_f - m_a;
+ m_a7 = (m_f + m_u) * m_a + m_h;
+ } else {
+ //--------------------------------------------------------------
+ // itype == 1 Indicates that all formulas are divided by m_c.
+ //--------------------------------------------------------------
+
+ itype = 1;
+ m_e = m_a / m_c;
+ m_f = m_d / m_c;
+ m_g = m_u * m_e;
+ m_h = m_v * m_b;
+ m_a3 = m_a * m_e + (m_h / m_c + m_g) * m_b;
+ m_a1 = m_b - m_a * (m_d / m_c);
+ m_a7 = m_a + m_g * m_d + m_h * m_f;
+ }
+
+ return itype;
+}
+
+//======================================================================
+// Computes the next k polynomials using scalars computed in CalcSc.
+//======================================================================
+
+void PolynomialRootFinder::NextK(int itype) {
+ int ii = 0;
+
+ if (itype == 3) {
+ //--------------------------------------------------------------
+ // Use unscaled form of the recurrence if type is 3.
+ //--------------------------------------------------------------
+
+ m_k_vector_ptr[0] = 0.0;
+ m_k_vector_ptr[1] = 0.0;
+
+ for (ii = 2; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] = m_qk_vector_ptr[ii - 2];
+ }
+ } else {
+ double temp = m_a;
+
+ if (itype == 1) {
+ temp = m_b;
+ }
+
+ if (::fabs(m_a1) <= ::fabs(temp) * f_ETA_N) {
+ //----------------------------------------------------------
+ // If m_a1 is nearly zero then use a special form of
+ // the recurrence.
+ //----------------------------------------------------------
+
+ m_k_vector_ptr[0] = 0.0;
+ m_k_vector_ptr[1] = -m_a7 * m_qp_vector_ptr[0];
+
+ for (ii = 2; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] =
+ m_a3 * m_qk_vector_ptr[ii - 2] - m_a7 * m_qp_vector_ptr[ii - 1];
+ }
+ } else {
+ //----------------------------------------------------------
+ // Use scaled form of the recurrence.
+ //----------------------------------------------------------
+
+ m_a7 = m_a7 / m_a1;
+ m_a3 = m_a3 / m_a1;
+ m_k_vector_ptr[0] = m_qp_vector_ptr[0];
+ m_k_vector_ptr[1] = m_qp_vector_ptr[1] - m_a7 * m_qp_vector_ptr[0];
+
+ for (ii = 2; ii < m_n; ++ii) {
+ m_k_vector_ptr[ii] = m_a3 * m_qk_vector_ptr[ii - 2] -
+ m_a7 * m_qp_vector_ptr[ii - 1] +
+ m_qp_vector_ptr[ii];
+ }
+ }
+ }
+
+ return;
+}
+
+//======================================================================
+// Compute new estimates of the quadratic coefficients using the
+// scalars computed in CalcSc.
+//======================================================================
+
+void PolynomialRootFinder::Newest(int itype, double &uu, double &vv) {
+ //------------------------------------------------------------------
+ // Use formulas appropriate to setting of itype.
+ //------------------------------------------------------------------
+
+ if (itype == 3) {
+ //--------------------------------------------------------------
+ // If itype == 3 the quadratic is zeroed.
+ //--------------------------------------------------------------
+
+ uu = 0.0;
+ vv = 0.0;
+ } else {
+ double a4;
+ double a5;
+
+ if (itype == 2) {
+ a4 = (m_a + m_g) * m_f + m_h;
+ a5 = (m_f + m_u) * m_c + m_v * m_d;
+ } else {
+ a4 = m_a + m_u * m_b + m_h * m_f;
+ a5 = m_c + (m_u + m_v * m_f) * m_d;
+ }
+
+ //--------------------------------------------------------------
+ // Evaluate new quadratic coefficients.
+ //--------------------------------------------------------------
+
+ double b1 = -m_k_vector_ptr[m_n - 1] / m_p_vector_ptr[m_n];
+ double b2 = -(m_k_vector_ptr[m_n - 2] + b1 * m_p_vector_ptr[m_n - 1]) /
+ m_p_vector_ptr[m_n];
+ double c1 = m_v * b2 * m_a1;
+ double c2 = b1 * m_a7;
+ double c3 = b1 * b1 * m_a3;
+ double c4 = c1 - c2 - c3;
+ double temp = a5 + b1 * a4 - c4;
+
+ if (temp != 0.0) {
+ uu = m_u - (m_u * (c3 + c2) + m_v * (b1 * m_a1 + b2 * m_a7)) / temp;
+ vv = m_v * (1.0 + c4 / temp);
+ }
+ }
+
+ return;
+}
+
+//======================================================================
+// Divides p by the quadratic 1, u, v placing the quotient in q
+// and the remainder in a,b
+//======================================================================
+
+void PolynomialRootFinder::QuadraticSyntheticDivision(int n_plus_one, double u,
+ double v, double *p_ptr,
+ double *q_ptr, double &a,
+ double &b) {
+ b = p_ptr[0];
+ q_ptr[0] = b;
+ a = p_ptr[1] - u * b;
+ q_ptr[1] = a;
+
+ int ii = 0;
+
+ for (ii = 2; ii < n_plus_one; ++ii) {
+ double c = p_ptr[ii] - u * a - v * b;
+ q_ptr[ii] = c;
+ b = a;
+ a = c;
+ }
+
+ return;
+}
+
+//======================================================================
+// 2
+// Calculate the zeros of the quadratic a x + b x + c.
+// the quadratic formula, modified to avoid overflow, is used to find
+// the larger zero if the zeros are real and both zeros are complex.
+// the smaller real zero is found directly from the product of the
+// zeros c / a.
+//======================================================================
+
+void PolynomialRootFinder::SolveQuadraticEquation(double a, double b, double c,
+ double &sr, double &si,
+ double &lr, double &li) {
+ if (a == 0.0) {
+ if (b != 0.0) {
+ sr = -c / b;
+ } else {
+ sr = 0.0;
+ }
+
+ lr = 0.0;
+ si = 0.0;
+ li = 0.0;
+ } else if (c == 0.0) {
+ sr = 0.0;
+ lr = -b / a;
+ si = 0.0;
+ li = 0.0;
+ } else {
+ //--------------------------------------------------------------
+ // Compute discriminant avoiding overflow.
+ //--------------------------------------------------------------
+
+ double d;
+ double e;
+ double bvar = b / 2.0;
+
+ if (::fabs(bvar) < ::fabs(c)) {
+ if (c < 0.0) {
+ e = -a;
+ } else {
+ e = a;
+ }
+
+ e = bvar * (bvar / ::fabs(c)) - e;
+
+ d = ::sqrt(::fabs(e)) * ::sqrt(::fabs(c));
+ } else {
+ e = 1.0 - (a / bvar) * (c / bvar);
+ d = ::sqrt(::fabs(e)) * ::fabs(bvar);
+ }
+
+ if (e >= 0.0) {
+ //----------------------------------------------------------
+ // Real zeros
+ //----------------------------------------------------------
+
+ if (bvar >= 0.0) {
+ d = -d;
+ }
+
+ lr = (-bvar + d) / a;
+ sr = 0.0;
+
+ if (lr != 0.0) {
+ sr = (c / lr) / a;
+ }
+
+ si = 0.0;
+ li = 0.0;
+ } else {
+ //----------------------------------------------------------
+ // Complex conjugate zeros
+ //----------------------------------------------------------
+
+ sr = -bvar / a;
+ lr = sr;
+ si = ::fabs(d / a);
+ li = -si;
+ }
+ }
+
+ return;
+}
diff --git a/PolynomialRootFinder.h b/PolynomialRootFinder.h
new file mode 100644
index 0000000..ab80649
--- /dev/null
+++ b/PolynomialRootFinder.h
@@ -0,0 +1,136 @@
+//=======================================================================
+// Copyright (C) 2003-2013 William Hallahan
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software,
+// and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//=======================================================================
+
+//**********************************************************************
+// File: PolynomialRootFinder.h
+// Author: Bill Hallahan
+// Date: January 30, 2003
+//
+// Abstract:
+//
+// This file contains the definition for class PolynomialRootFinder.
+//
+//**********************************************************************
+
+#ifndef POLYNOMIALROOTFINDER_H
+#define POLYNOMIALROOTFINDER_H
+
+#include
+
+//======================================================================
+// Class definition.
+//======================================================================
+
+class PolynomialRootFinder {
+protected:
+ typedef double PRF_Float_T;
+
+ std::vector m_p_vector;
+ std::vector m_qp_vector;
+ std::vector m_k_vector;
+ std::vector m_qk_vector;
+ std::vector m_svk_vector;
+
+ double *m_p_vector_ptr;
+ double *m_qp_vector_ptr;
+ double *m_k_vector_ptr;
+ double *m_qk_vector_ptr;
+ double *m_svk_vector_ptr;
+
+ int m_degree;
+ int m_n;
+ int m_n_plus_one;
+ double m_real_s;
+ double m_imag_s;
+ double m_u;
+ double m_v;
+ double m_a;
+ double m_b;
+ double m_c;
+ double m_d;
+ double m_a1;
+ double m_a2;
+ double m_a3;
+ double m_a6;
+ double m_a7;
+ double m_e;
+ double m_f;
+ double m_g;
+ double m_h;
+ double m_real_sz;
+ double m_imag_sz;
+ double m_real_lz;
+ double m_imag_lz;
+ PRF_Float_T m_are;
+ PRF_Float_T m_mre;
+
+public:
+ enum RootStatus_T {
+ SUCCESS,
+ LEADING_COEFFICIENT_IS_ZERO,
+ SCALAR_VALUE_HAS_NO_ROOTS,
+ FAILED_TO_CONVERGE
+ };
+
+ PolynomialRootFinder();
+
+ virtual ~PolynomialRootFinder();
+
+ PolynomialRootFinder::RootStatus_T
+ FindRoots(double *coefficient_ptr, int degree, double *real_zero_vector_ptr,
+ double *imaginary_zero_vector_ptr,
+ int *number_of_roots_found_ptr = 0);
+
+private:
+ int Fxshfr(int l2var);
+
+ int QuadraticIteration(double uu, double vv);
+
+ int RealIteration(double &sss, int &flag);
+
+ int CalcSc();
+
+ void NextK(int itype);
+
+ void Newest(int itype, double &uu, double &vv);
+
+ void QuadraticSyntheticDivision(int n_plus_one, double u, double v,
+ double *p_ptr, double *q_ptr, double &a,
+ double &b);
+
+ void SolveQuadraticEquation(double a, double b, double c, double &sr,
+ double &si, double &lr, double &li);
+
+ //==================================================================
+ // Declare the copy constructor and operator equals to be private
+ // and do not implement them to prevent copying instances of this
+ // class.
+ //==================================================================
+
+ PolynomialRootFinder(const PolynomialRootFinder &that);
+
+ PolynomialRootFinder operator=(const PolynomialRootFinder &that);
+};
+
+#endif
diff --git a/PolynomialTest.cpp b/PolynomialTest.cpp
new file mode 100644
index 0000000..5ac2041
--- /dev/null
+++ b/PolynomialTest.cpp
@@ -0,0 +1,450 @@
+//=======================================================================
+// Copyright (C) 2003-2013 William Hallahan
+//
+// Permission is hereby granted, free of charge, to any person
+// obtaining a copy of this software and associated documentation
+// files (the "Software"), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge,
+// publish, distribute, sublicense, and/or sell copies of the Software,
+// and to permit persons to whom the Software is furnished to do so,
+// subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+// OTHER DEALINGS IN THE SOFTWARE.
+//=======================================================================
+
+// PolynomialTest.cpp : Defines the entry point for the console application.
+//
+
+#include "Polynomial.h"
+#include
+#include
+
+void DisplayPolynomial(const Polynomial &polynomial);
+void GetPolynomial(Polynomial &polynomial, int polynomial_type);
+
+//======================================================================
+// Start of main program.
+//======================================================================
+
+int main(int argc, char *argv[]) {
+ //------------------------------------------------------------------
+ // Get the type of test.
+ //------------------------------------------------------------------
+
+ std::cout << std::endl;
+ std::cout << "1. Find roots of the polynomial." << std::endl;
+ std::cout << "2. Evaluate the polynomial at a real value" << std::endl;
+ std::cout << "3. Evaluate the polynomial and its derivative at a real value"
+ << std::endl;
+ std::cout << "4. Evaluate the polynomial at a complex value" << std::endl;
+ std::cout
+ << "5. Evaluate the polynomial and its derivative at a complex value"
+ << std::endl;
+ std::cout << "6. Test polynomial arithmetic." << std::endl;
+ std::cout << "7. Test polynomial division." << std::endl;
+ std::cout << std::endl;
+ std::cout << "Enter the type of test > ";
+ int test_type;
+ std::cin >> test_type;
+
+ //------------------------------------------------------------------
+ // Get the type of polynomial.
+ //------------------------------------------------------------------
+
+ std::cout << "1. Arbitrary polynomial" << std::endl;
+ std::cout
+ << "2. Polynomial with maximum power and scalar value 1.0, the rest 0.0."
+ << std::endl;
+ std::cout << "3. Polynomial with all coefficient equal to 1.0." << std::endl;
+ std::cout << std::endl;
+ std::cout << "Enter the type of polynomial > ";
+ int polynomial_type;
+ std::cin >> polynomial_type;
+ std::cout << std::endl;
+
+ //------------------------------------------------------------------
+ // Get a polynomial.
+ //------------------------------------------------------------------
+
+ Polynomial polynomial;
+
+ GetPolynomial(polynomial, polynomial_type);
+
+ //------------------------------------------------------------------
+ // Perform different processing for the different tests.
+ //------------------------------------------------------------------
+
+ switch (test_type) {
+ case 1: {
+ //----------------------------------------------------------
+ // Find the roots of the polynomial.
+ //----------------------------------------------------------
+
+ std::vector real_vector;
+ std::vector imag_vector;
+
+ int degree = polynomial.Degree();
+
+ real_vector.resize(degree);
+ imag_vector.resize(degree);
+
+ double *real_vector_ptr = &real_vector[0];
+ double *imag_vector_ptr = &imag_vector[0];
+
+ int root_count = 0;
+
+ if (polynomial.FindRoots(real_vector_ptr, imag_vector_ptr, &root_count) ==
+ PolynomialRootFinder::SUCCESS) {
+ int i = 0;
+
+ for (i = 0; i < root_count; ++i) {
+ std::cout << "Root " << i << " = " << real_vector_ptr[i] << " + i "
+ << imag_vector_ptr[i] << std::endl;
+ }
+ } else {
+ std::cout << "Failed to find all roots." << std::endl;
+ }
+ }
+
+ break;
+
+ case 2: {
+ //----------------------------------------------------------
+ // Evaluate the polynomial at a real value.
+ //----------------------------------------------------------
+
+ while (true) {
+ std::cout << "Enter value > ";
+ double xr;
+ std::cin >> xr;
+ std::cout << "P(" << xr << ") = " << polynomial.EvaluateReal(xr)
+ << std::endl;
+ std::cout << std::endl;
+ }
+ }
+
+ break;
+
+ case 3: {
+ //----------------------------------------------------------
+ // Evaluate the polynomial and its derivative at a
+ // real value.
+ //----------------------------------------------------------
+
+ while (true) {
+ std::cout << "Enter value > ";
+ double xr;
+ std::cin >> xr;
+
+ double dr;
+ double pr = polynomial.EvaluateReal(xr, dr);
+
+ std::cout << "P(" << xr << ") = " << pr << std::endl;
+ std::cout << "D(" << xr << ") = " << dr << std::endl;
+ std::cout << std::endl;
+ }
+ }
+
+ break;
+
+ case 4: {
+ //----------------------------------------------------------
+ // Evaluate the polynomial at a complex value.
+ //----------------------------------------------------------
+
+ while (true) {
+ std::cout << "Enter real value > ";
+ double xr;
+ std::cin >> xr;
+
+ std::cout << "Enter imaginary value > ";
+ double xi;
+ std::cin >> xi;
+
+ double pr;
+ double pi;
+
+ polynomial.EvaluateComplex(xr, xi, pr, pi);
+
+ std::cout << "P(" << xr << " + i " << xi << ") = " << pr << " + i " << pi
+ << std::endl;
+ std::cout << std::endl;
+ }
+ }
+
+ break;
+
+ case 5: {
+ //----------------------------------------------------------
+ // Evaluate the polynomial and its derivative at a
+ // complex value.
+ //----------------------------------------------------------
+
+ while (true) {
+ std::cout << "Enter real value > ";
+ double xr;
+ std::cin >> xr;
+
+ std::cout << "Enter imaginary value > ";
+ double xi;
+ std::cin >> xi;
+
+ double pr;
+ double pi;
+ double dr;
+ double di;
+
+ polynomial.EvaluateComplex(xr, xi, pr, pi, dr, di);
+
+ std::cout << "P(" << xr << " + i " << xi << ") = " << pr << " + i " << pi
+ << std::endl;
+ std::cout << "D(" << xr << " + i " << xi << ") = " << dr << " + i " << di
+ << std::endl;
+ std::cout << std::endl;
+ }
+ }
+
+ break;
+
+ case 6: {
+ //----------------------------------------------------------
+ // Test polynomial arithmetic.
+ // Test polynomial copy constructor and equals operator.
+ //----------------------------------------------------------
+
+ Polynomial p_0 = polynomial;
+ Polynomial p_1;
+ p_1 = p_0;
+
+ //----------------------------------------------------------
+ // Test polynomial addition.
+ //----------------------------------------------------------
+
+ Polynomial p_sum = p_0 + p_1;
+
+ std::cout << "The sum polynomial is:" << std::endl;
+ std::cout << std::endl;
+ DisplayPolynomial(p_sum);
+ std::cout << std::endl;
+
+ //----------------------------------------------------------
+ // Test polynomial subtraction.
+ //----------------------------------------------------------
+
+ std::cout << "The difference polynomial is:" << std::endl;
+ Polynomial p_diff = p_0 - p_1;
+ std::cout << std::endl;
+ DisplayPolynomial(p_diff);
+ std::cout << std::endl;
+
+ //----------------------------------------------------------
+ // Test polynomial multiplication.
+ //----------------------------------------------------------
+
+ std::cout << "The product polynomial is:" << std::endl;
+ Polynomial p_product = p_0 * p_1;
+ std::cout << std::endl;
+ DisplayPolynomial(p_product);
+ std::cout << std::endl;
+ }
+
+ break;
+
+ case 7: {
+ //----------------------------------------------------------
+ // Get another polynomial that will be the divisor.
+ //----------------------------------------------------------
+
+ std::cout << "Enter the divisor polynomial." << std::endl;
+
+ Polynomial divisor_polynomial;
+ GetPolynomial(divisor_polynomial, 1);
+
+ Polynomial quotient_polynomial;
+ Polynomial remainder_polynomial;
+
+ polynomial.Divide(divisor_polynomial, quotient_polynomial,
+ remainder_polynomial);
+
+ //----------------------------------------------------------
+ // Display the quotient polynomial.
+ //----------------------------------------------------------
+
+ std::cout << "The quotient polynomial is:" << std::endl;
+ std::cout << std::endl;
+ DisplayPolynomial(quotient_polynomial);
+ std::cout << std::endl;
+
+ //----------------------------------------------------------
+ // Display the remainder polynomial.
+ //----------------------------------------------------------
+
+ std::cout << "The remainder polynomial is:" << std::endl;
+ std::cout << std::endl;
+ DisplayPolynomial(remainder_polynomial);
+ std::cout << std::endl;
+ }
+
+ break;
+
+ default:
+
+ std::cout << "Invalid test type" << std::endl;
+ return -1;
+ break;
+ }
+
+ return 0;
+}
+
+//======================================================================
+// Function to display a polynomial.
+//======================================================================
+
+void DisplayPolynomial(const Polynomial &polynomial) {
+ int power = 0;
+
+ for (power = polynomial.Degree(); power > 0; --power) {
+ //--------------------------------------------------------------
+ // Display the coefficient if it is not equal to one.
+ //--------------------------------------------------------------
+
+ if (polynomial[power] != 1.0) {
+ std::cout << polynomial[power];
+ }
+
+ //--------------------------------------------------------------
+ // If this is not the scalar value, then display the variable
+ // X.
+ //--------------------------------------------------------------
+
+ if (power > 0) {
+ std::cout << " X";
+ }
+
+ //--------------------------------------------------------------
+ // If this is higher than the first power, then display the
+ // exponent.
+ //--------------------------------------------------------------
+
+ if (power > 1) {
+ std::cout << "^" << power;
+ }
+
+ //--------------------------------------------------------------
+ // Add each term together.
+ //--------------------------------------------------------------
+
+ std::cout << " + ";
+ }
+
+ //------------------------------------------------------------------
+ // Display the polynomial's scalar value.
+ //------------------------------------------------------------------
+
+ std::cout << polynomial[power] << std::endl;
+
+ return;
+}
+
+//======================================================================
+// Function: GetPolynomial
+//======================================================================
+
+void GetPolynomial(Polynomial &polynomial, int polynomial_type) {
+ //------------------------------------------------------------------
+ // Get the polynomial degree.
+ //------------------------------------------------------------------
+
+ std::cout << "Enter the polynomial degree > ";
+ int degree = 0;
+ std::cin >> degree;
+ std::cout << std::endl;
+
+ //------------------------------------------------------------------
+ // Create a buffer to contain the polynomial coefficients.
+ //------------------------------------------------------------------
+
+ std::vector coefficient_vector;
+
+ coefficient_vector.resize(degree + 1);
+
+ double *coefficient_vector_ptr = &coefficient_vector[0];
+
+ //------------------------------------------------------------------
+ // Create the specified type of polynomial.
+ //------------------------------------------------------------------
+
+ int i = 0;
+
+ switch (polynomial_type) {
+ case 1:
+
+ //--------------------------------------------------------------
+ // Create an arbitrary polynomial.
+ //--------------------------------------------------------------
+
+ for (i = 0; i <= degree; ++i) {
+ std::cout << "coefficient[" << i << "] = ";
+ double temp;
+ ;
+ std::cin >> temp;
+ coefficient_vector_ptr[i] = temp;
+ }
+
+ std::cout << std::endl;
+ break;
+
+ case 2:
+
+ //--------------------------------------------------------------
+ // Create a polynomial with the maximum degree and the scalar
+ // value coefficients equal to 1.0 and all other coefficients
+ // equal to zero.
+ //--------------------------------------------------------------
+
+ for (i = 1; i < degree; ++i) {
+ coefficient_vector_ptr[i] = 0;
+ }
+
+ coefficient_vector_ptr[0] = 1.0;
+ coefficient_vector_ptr[degree] = 1.0;
+
+ break;
+
+ case 3:
+
+ //--------------------------------------------------------------
+ // Create a polynomial with all coefficients equal to 1.0.
+ //--------------------------------------------------------------
+
+ for (i = 0; i <= degree; ++i) {
+ coefficient_vector_ptr[i] = 1.0;
+ }
+
+ break;
+
+ default:
+
+ std::cout << "Invalid polynomial type" << std::endl;
+ exit(-1);
+ }
+
+ //------------------------------------------------------------------
+ // Create an instance of class Polynomial.
+ //------------------------------------------------------------------
+
+ polynomial.SetCoefficients(coefficient_vector_ptr, degree);
+
+ return;
+}
diff --git a/R-plotter.r b/R-plotter.r
new file mode 100644
index 0000000..ed8c037
--- /dev/null
+++ b/R-plotter.r
@@ -0,0 +1,19 @@
+rm(list = ls())
+library(ggplot2) #Needs ggplot2 - run install.packages(ggplot2) if not already installed !!
+
+cols <- hcl.colors(30, "Spectral")
+
+Ne = 10000 #Quantities needed to recale time back into years before present
+g = 5
+
+ImpT <- t(read.table("D:/MCMC4WF-ThetaZero/ImpT.txt", quote = "\"", comment.char = "")) #Input location of file ImpT.txt here!
+ImpT <-(((ImpT * 2 * Ne * g) - 20000)) #Converting from diffusion time to years before present
+ImpHT <-(t(read.table("D:/MCMC4WF-ThetaZero/HorseTrajectories.txt", quote = "\"", comment.char = ""))) #Input location of file ImpHT.txt here!
+OGT <-t(read.table("D:/MCMC4WF-ThetaZero/OGT.txt", quote = "\"", comment.char = "")) #Input location of file OGT.txt here!
+OGT <-(((OGT * 2 * Ne * g) - 20000)) #Converting from diffusion time to years before present
+OGHT <-(t(read.table("D:/MCMC4WF-ThetaZero/OGHT.txt", quote = "\"", comment.char = ""))) #Input location of file OGHT.txt here
+
+setEPS()
+postscript(file = "horseTrajectories.eps") #Selection of figure format
+matplot(ImpT, ImpHT, type = "l", col = cols, lwd = 1, lty = 1, xlab = "Time in years before present", ylab = "Frequency", ylim = c(0, 0.85)) #Plots all the generated paths
+points(OGT, OGHT, pch = 4, bg = "black", col = "black", lwd = 4, cex = 1.5) #Superimposes the original observations dev.off()
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fa091b7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,34 @@
+#EWF
+
+An efficient simulator for exact Wright-Fisher diffusion and diffusion bridge paths, accounting for a wide class of selective regimes (genic, diploid and arbitrary polynomial selection), and the presence/absence of mutation.
+
+*Dependencies*
+
+EWF has been tested out on Ubuntu 20.04, and requires the following:
+
+- g++ compiler (tested on version 9.4.0)
+- libconfig library (tested on version 1.7.3), available from http://hyperrealm.github.io/libconfig
+- boost library (tested on version 1.78.0), available from https://boost.org
+- R (tested on version 4.2.1 using RStudio version 2022.07.1+554), available from https://www.r-project.org/
+
+*Compilation*
+
+Please ensure that the compiler and linker flags in 'Makefile' point towards where the 'libconfig' and 'boost' libraries are on your platform!
+
+*Configuration files*
+
+The underlying Wright-Fisher diffusion/diffusion bridge can be configured via the 'config.cfg' file, where the mutation and selection parameters can be suitably altered.
+
+The configuration setup for simulating draws from the law of a _diffusion_ are found in 'configDiffusion.cfg' which allows for the start points, start times and sample times to be modified (as well as number of samples to generate and mesh size if the truncated transition density is desired). If multiple simulation setups are desired, the corresponding setup inputs need to be entered as an array. Precise instructions on input syntax can be found in the file itself.
+
+The configuration setup for simulating draws from the law of a _diffusion bridge_ are found in 'configBridge.cfg' which allows for the start/end points and times, sampling times, number of bridges to simulate, etc. to be modified. Please see the details within the configuration file for exact instructions with regards to input syntax. The number of simulations and mesh sizes (for the truncated transition density) can also be modified.
+
+*Running the program*
+
+When in the root directory run 'run.sh'. This first compiles the program by invoking the makefile, and subsequently calls the program using './main horses' where the second argument invokes the demo described below. The program can be run as a diffusion or diffusion bridge simulator by changing the program invocation to simply './main', whence the program asks whether the user desires to simulate draws from a diffusion law or from a diffusion bridge law, whether they wish to condition on non-absorption and further offers the option of computing a truncation to the transition density.
+
+*Output files*
+
+Output for the diffusion simulator is saved using the format 'YYYY-MM-DD-HH-mmAbsDiffusionSamplesX%T%S%.txt' for the samples generated (where 'Abs' is either 'Conditioned' (if absorption is not allowed at the boundaries) or 'Unconditioned' (if absorption at the boundaries is allowed), 'T' denotes the start time and 'S' the sampling time), and 'YYYY-MM-DD-HH-mmAbsDiffusionDensityX%T%S%.txt' for the truncated transition density.
+
+A similar system is in place for the diffusion bridge simulator, where the output is saved as 'YYYY-MM-DD-HH-mmAbsBridgeSamplesX%Z%T1%T2%S%.txt' with 'X' denoting the start point, 'Z' the end point, 'T1' the start time, 'T2' the end time and 'S' the sampling time. A similar setup is in place for the truncated transition density.
diff --git a/WrightFisher.cpp b/WrightFisher.cpp
new file mode 100644
index 0000000..75953e4
--- /dev/null
+++ b/WrightFisher.cpp
@@ -0,0 +1,9819 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include