cpp/0000755000175000017500000000000013576650314011230 5ustar sergeysergeycpp/gpl3.txt0000755000175000017500000010575313576650314012654 0ustar sergeysergey GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .cpp/tests/0000755000175000017500000000000013576650314012372 5ustar sergeysergeycpp/tests/test_i.cpp0000755000175000017500000210707513576650313014403 0ustar sergeysergey#include "stdafx.h" #include #include "alglibinternal.h" #include "alglibmisc.h" #include "diffequations.h" #include "linalg.h" #include "optimization.h" #include "solvers.h" #include "statistics.h" #include "dataanalysis.h" #include "specialfunctions.h" #include "integration.h" #include "fasttransforms.h" #include "interpolation.h" using namespace alglib; bool doc_test_bool(bool v, bool t) { return (v && t) || (!v && !t); } bool doc_test_int(ae_int_t v, ae_int_t t) { return v==t; } bool doc_test_real(double v, double t, double _threshold) { double s = _threshold>=0 ? 1.0 : fabs(t); double threshold = fabs(_threshold); return fabs(v-t)/s<=threshold; } bool doc_test_complex(alglib::complex v, alglib::complex t, double _threshold) { double s = _threshold>=0 ? 1.0 : alglib::abscomplex(t); double threshold = fabs(_threshold); return abscomplex(v-t)/s<=threshold; } bool doc_test_bool_vector(const boolean_1d_array &v, const boolean_1d_array &t) { ae_int_t i; if( v.length()!=t.length() ) return false; for(i=0; i=0 ? 1.0 : fabs(t(i)); double threshold = fabs(_threshold); if( fabs(v(i)-t(i))/s>threshold ) return false; } return true; } bool doc_test_real_matrix(const real_2d_array &v, const real_2d_array &t, double _threshold) { ae_int_t i, j; if( v.rows()!=t.rows() ) return false; if( v.cols()!=t.cols() ) return false; for(i=0; i=0 ? 1.0 : fabs(t(i,j)); double threshold = fabs(_threshold); if( fabs(v(i,j)-t(i,j))/s>threshold ) return false; } return true; } bool doc_test_complex_vector(const complex_1d_array &v, const complex_1d_array &t, double _threshold) { ae_int_t i; if( v.length()!=t.length() ) return false; for(i=0; i=0 ? 1.0 : alglib::abscomplex(t(i)); double threshold = fabs(_threshold); if( abscomplex(v(i)-t(i))/s>threshold ) return false; } return true; } bool doc_test_complex_matrix(const complex_2d_array &v, const complex_2d_array &t, double _threshold) { ae_int_t i, j; if( v.rows()!=t.rows() ) return false; if( v.cols()!=t.cols() ) return false; for(i=0; i=0 ? 1.0 : alglib::abscomplex(t(i,j)); double threshold = fabs(_threshold); if( abscomplex(v(i,j)-t(i,j))/s>threshold ) return false; } return true; } template void spoil_vector_by_adding_element(T &x) { ae_int_t i; T y = x; x.setlength(y.length()+1); for(i=0; i void spoil_vector_by_deleting_element(T &x) { ae_int_t i; T y = x; x.setlength(y.length()-1); for(i=0; i void spoil_matrix_by_adding_row(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows()+1, y.cols()); for(i=0; i void spoil_matrix_by_deleting_row(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows()-1, y.cols()); for(i=0; i void spoil_matrix_by_adding_col(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows(), y.cols()+1); for(i=0; i void spoil_matrix_by_deleting_col(T &x) { ae_int_t i, j; T y = x; x.setlength(y.rows(), y.cols()-1); for(i=0; i void spoil_vector_by_nan(T &x) { if( x.length()!=0 ) x(randominteger(x.length())) = fp_nan; } template void spoil_vector_by_posinf(T &x) { if( x.length()!=0 ) x(randominteger(x.length())) = fp_posinf; } template void spoil_vector_by_neginf(T &x) { if( x.length()!=0 ) x(randominteger(x.length())) = fp_neginf; } template void spoil_matrix_by_nan(T &x) { if( x.rows()!=0 && x.cols()!=0 ) x(randominteger(x.rows()),randominteger(x.cols())) = fp_nan; } template void spoil_matrix_by_posinf(T &x) { if( x.rows()!=0 && x.cols()!=0 ) x(randominteger(x.rows()),randominteger(x.cols())) = fp_posinf; } template void spoil_matrix_by_neginf(T &x) { if( x.rows()!=0 && x.cols()!=0 ) x(randominteger(x.rows()),randominteger(x.cols())) = fp_neginf; } void function1_func(const real_1d_array &x, double &func, void *ptr) { // // this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4 // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); } void function1_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4 // and its derivatives df/d0 and df/dx1 // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 400*pow(x[0]+3,3); grad[1] = 4*pow(x[1]-3,3); } void function1_hess(const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // // this callback calculates f(x0,x1) = 100*(x0+3)^4 + (x1-3)^4 // its derivatives df/d0 and df/dx1 // and its Hessian. // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 400*pow(x[0]+3,3); grad[1] = 4*pow(x[1]-3,3); hess[0][0] = 1200*pow(x[0]+3,2); hess[0][1] = 0; hess[1][0] = 0; hess[1][1] = 12*pow(x[1]-3,2); } void function1_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates // f0(x0,x1) = 100*(x0+3)^4, // f1(x0,x1) = (x1-3)^4 // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); } void function1_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // f0(x0,x1) = 100*(x0+3)^4, // f1(x0,x1) = (x1-3)^4 // and Jacobian matrix J = [dfi/dxj] // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); jac[0][0] = 20*(x[0]+3); jac[0][1] = 0; jac[1][0] = 0; jac[1][1] = 2*(x[1]-3); } void function2_func(const real_1d_array &x, double &func, void *ptr) { // // this callback calculates f(x0,x1) = (x0^2+1)^2 + (x1-1)^2 // func = pow(x[0]*x[0]+1,2) + pow(x[1]-1,2); } void function2_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates f(x0,x1) = (x0^2+1)^2 + (x1-1)^2 // and its derivatives df/d0 and df/dx1 // func = pow(x[0]*x[0]+1,2) + pow(x[1]-1,2); grad[0] = 4*(x[0]*x[0]+1)*x[0]; grad[1] = 2*(x[1]-1); } void function2_hess(const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // // this callback calculates f(x0,x1) = (x0^2+1)^2 + (x1-1)^2 // its gradient and Hessian // func = pow(x[0]*x[0]+1,2) + pow(x[1]-1,2); grad[0] = 4*(x[0]*x[0]+1)*x[0]; grad[1] = 2*(x[1]-1); hess[0][0] = 12*x[0]*x[0]+4; hess[0][1] = 0; hess[1][0] = 0; hess[1][1] = 2; } void function2_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates // f0(x0,x1) = x0^2+1 // f1(x0,x1) = x1-1 // fi[0] = x[0]*x[0]+1; fi[1] = x[1]-1; } void function2_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // f0(x0,x1) = x0^2+1 // f1(x0,x1) = x1-1 // and Jacobian matrix J = [dfi/dxj] // fi[0] = x[0]*x[0]+1; fi[1] = x[1]-1; jac[0][0] = 2*x[0]; jac[0][1] = 0; jac[1][0] = 0; jac[1][1] = 1; } void nlcfunc1_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // // f0(x0,x1) = -x0+x1 // f1(x0,x1) = x0^2+x1^2-1 // // and Jacobian matrix J = [dfi/dxj] // fi[0] = -x[0]+x[1]; fi[1] = x[0]*x[0] + x[1]*x[1] - 1.0; jac[0][0] = -1.0; jac[0][1] = +1.0; jac[1][0] = 2*x[0]; jac[1][1] = 2*x[1]; } void nlcfunc2_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // // f0(x0,x1,x2) = x0+x1 // f1(x0,x1,x2) = x2-exp(x0) // f2(x0,x1,x2) = x0^2+x1^2-1 // // and Jacobian matrix J = [dfi/dxj] // fi[0] = x[0]+x[1]; fi[1] = x[2]-exp(x[0]); fi[2] = x[0]*x[0] + x[1]*x[1] - 1.0; jac[0][0] = 1.0; jac[0][1] = 1.0; jac[0][2] = 0.0; jac[1][0] = -exp(x[0]); jac[1][1] = 0.0; jac[1][2] = 1.0; jac[2][0] = 2*x[0]; jac[2][1] = 2*x[1]; jac[2][2] = 0.0; } void nsfunc1_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates // // f0(x0,x1) = 2*|x0|+x1 // // and Jacobian matrix J = [df0/dx0 df0/dx1] // fi[0] = 2*fabs(double(x[0]))+fabs(double(x[1])); jac[0][0] = 2*alglib::sign(x[0]); jac[0][1] = alglib::sign(x[1]); } void nsfunc1_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates // // f0(x0,x1) = 2*|x0|+x1 // fi[0] = 2*fabs(double(x[0]))+fabs(double(x[1])); } void nsfunc2_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates function vector // // f0(x0,x1) = 2*|x0|+x1 // f1(x0,x1) = x0-1 // f2(x0,x1) = -x1-1 // // and Jacobian matrix J // // [ df0/dx0 df0/dx1 ] // J = [ df1/dx0 df1/dx1 ] // [ df2/dx0 df2/dx1 ] // fi[0] = 2*fabs(double(x[0]))+fabs(double(x[1])); jac[0][0] = 2*alglib::sign(x[0]); jac[0][1] = alglib::sign(x[1]); fi[1] = x[0]-1; jac[1][0] = 1; jac[1][1] = 0; fi[2] = -x[1]-1; jac[2][0] = 0; jac[2][1] = -1; } void bad_func(const real_1d_array &x, double &func, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); } void bad_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 40*pow(x[0]+3,3); grad[1] = 40*pow(x[1]-3,3); } void bad_hess(const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // func = 100*pow(x[0]+3,4) + pow(x[1]-3,4); grad[0] = 40*pow(x[0]+3,3); grad[1] = 40*pow(x[1]-3,3); hess[0][0] = 120*pow(x[0]+3,2); hess[0][1] = 0; hess[1][0] = 0; hess[1][1] = 120*pow(x[1]-3,2); } void bad_fvec(const real_1d_array &x, real_1d_array &fi, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); } void bad_jac(const real_1d_array &x, real_1d_array &fi, real_2d_array &jac, void *ptr) { // // this callback calculates 'bad' function, // i.e. function with incorrectly calculated derivatives // fi[0] = 10*pow(x[0]+3,2); fi[1] = pow(x[1]-3,2); jac[0][0] = 2*(x[0]+3); jac[0][1] = 1; jac[1][0] = 0; jac[1][1] = 20*(x[1]-3); } void function_cx_1_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr) { // this callback calculates f(c,x)=exp(-c0*sqr(x0)) // where x is a position on X-axis and c is adjustable parameter func = exp(-c[0]*pow(x[0],2)); } void function_cx_1_grad(const real_1d_array &c, const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // this callback calculates f(c,x)=exp(-c0*sqr(x0)) and gradient G={df/dc[i]} // where x is a position on X-axis and c is adjustable parameter. // IMPORTANT: gradient is calculated with respect to C, not to X func = exp(-c[0]*pow(x[0],2)); grad[0] = -pow(x[0],2)*func; } void function_cx_1_hess(const real_1d_array &c, const real_1d_array &x, double &func, real_1d_array &grad, real_2d_array &hess, void *ptr) { // this callback calculates f(c,x)=exp(-c0*sqr(x0)), gradient G={df/dc[i]} and Hessian H={d2f/(dc[i]*dc[j])} // where x is a position on X-axis and c is adjustable parameter. // IMPORTANT: gradient/Hessian are calculated with respect to C, not to X func = exp(-c[0]*pow(x[0],2)); grad[0] = -pow(x[0],2)*func; hess[0][0] = pow(x[0],4)*func; } void ode_function_1_diff(const real_1d_array &y, double x, real_1d_array &dy, void *ptr) { // this callback calculates f(y[],x)=-y[0] dy[0] = -y[0]; } void int_function_1_func(double x, double xminusa, double bminusx, double &y, void *ptr) { // this callback calculates f(x)=exp(x) y = exp(x); } void function_debt_func(const real_1d_array &c, const real_1d_array &x, double &func, void *ptr) { // // this callback calculates f(c,x)=c[0]*(1+c[1]*(pow(x[0]-1999,c[2])-1)) // func = c[0]*(1+c[1]*(pow(x[0]-1999,c[2])-1)); } void s1_grad(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr) { // // this callback calculates f(x) = (1+x)^(-0.2) + (1-x)^(-0.3) + 1000*x and its gradient. // // function is trimmed when we calculate it near the singular points or outside of the [-1,+1]. // Note that we do NOT calculate gradient in this case. // if( (x[0]<=-0.999999999999) || (x[0]>=+0.999999999999) ) { func = 1.0E+300; return; } func = pow(1+x[0],-0.2) + pow(1-x[0],-0.3) + 1000*x[0]; grad[0] = -0.2*pow(1+x[0],-1.2) +0.3*pow(1-x[0],-1.3) + 1000; } int main() { bool _TotalResult = true; bool _TestResult; int _spoil_scenario; printf("C++ tests. Please wait...\n"); #if AE_MALLOC==AE_BASIC_STATIC_MALLOC const ae_int_t _static_pool_size = 1000000; ae_int_t _static_pool_used = 0, _static_pool_free = 0; void *_static_pool = malloc(_static_pool_size); alglib_impl::set_memory_pool(_static_pool, _static_pool_size); alglib_impl::memory_pool_stats(&_static_pool_used, &_static_pool_free); if( _static_pool_used!=0 || _static_pool_free<0.95*_static_pool_size || _static_pool_free>_static_pool_size ) { _TotalResult = false; printf("FAILURE: memory pool usage stats are inconsistent!\n"); return 1; } { alglib::real_2d_array a("[[1,2],[3,4]]"); ae_int_t _static_pool_used2 = 0, _static_pool_free2 = 0; alglib_impl::memory_pool_stats(&_static_pool_used2, &_static_pool_free2); if( _static_pool_used2<=_static_pool_used || _static_pool_free2>=_static_pool_free || _static_pool_used+_static_pool_free!=_static_pool_used2+_static_pool_free2 ) { _TotalResult = false; printf("FAILURE: memory pool usage stats are inconsistent!\n"); return 1; } a.setlength(1,1); // make sure that destructor of /a/ is never called prior to this point } #endif #ifdef AE_USE_ALLOC_COUNTER printf("Allocation counter activated...\n"); alglib_impl::_use_alloc_counter = ae_true; if( alglib_impl::_alloc_counter!=0 ) { _TotalResult = false; printf("FAILURE: alloc_counter is non-zero on start!\n"); } { { alglib::real_1d_array x; x.setlength(1); if( alglib_impl::_alloc_counter==0 ) printf(":::: WARNING: ALLOC_COUNTER IS INACTIVE!!! :::::\n"); } if( alglib_impl::_alloc_counter!=0 ) { printf("FAILURE: alloc_counter does not decrease!\n"); return 1; } } #endif try { // // TEST nneighbor_d_1 // Nearest neighbor search, KNN queries // printf("0/151\n"); _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { real_2d_array a = "[[0,0],[0,1],[1,0],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); ae_int_t nx = 2; ae_int_t ny = 0; ae_int_t normtype = 2; kdtree kdt; real_1d_array x; real_2d_array r = "[[]]"; ae_int_t k; kdtreebuild(a, nx, ny, normtype, kdt); x = "[-1,0]"; k = kdtreequeryknn(kdt, x, 1); _TestResult = _TestResult && doc_test_int(k, 1); kdtreequeryresultsx(kdt, r); _TestResult = _TestResult && doc_test_real_matrix(r, "[[0,0]]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nneighbor_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nneighbor_t_2 // Subsequent queries; buffered functions must use previously allocated storage (if large enough), so buffer may contain some info from previous call // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { real_2d_array a = "[[0,0],[0,1],[1,0],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); ae_int_t nx = 2; ae_int_t ny = 0; ae_int_t normtype = 2; kdtree kdt; real_1d_array x; real_2d_array rx = "[[]]"; ae_int_t k; kdtreebuild(a, nx, ny, normtype, kdt); x = "[+2,0]"; k = kdtreequeryknn(kdt, x, 2, true); _TestResult = _TestResult && doc_test_int(k, 2); kdtreequeryresultsx(kdt, rx); _TestResult = _TestResult && doc_test_real_matrix(rx, "[[1,0],[1,1]]", 0.05); x = "[-2,0]"; k = kdtreequeryknn(kdt, x, 1, true); _TestResult = _TestResult && doc_test_int(k, 1); kdtreequeryresultsx(kdt, rx); _TestResult = _TestResult && doc_test_real_matrix(rx, "[[0,0],[1,1]]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nneighbor_t_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST nneighbor_d_2 // Serialization of KD-trees // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { real_2d_array a = "[[0,0],[0,1],[1,0],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); ae_int_t nx = 2; ae_int_t ny = 0; ae_int_t normtype = 2; kdtree kdt0; kdtree kdt1; std::string s; real_1d_array x; real_2d_array r0 = "[[]]"; real_2d_array r1 = "[[]]"; // // Build tree and serialize it // kdtreebuild(a, nx, ny, normtype, kdt0); alglib::kdtreeserialize(kdt0, s); alglib::kdtreeunserialize(s, kdt1); // // Compare results from KNN queries // x = "[-1,0]"; kdtreequeryknn(kdt0, x, 1); kdtreequeryresultsx(kdt0, r0); kdtreequeryknn(kdt1, x, 1); kdtreequeryresultsx(kdt1, r1); _TestResult = _TestResult && doc_test_real_matrix(r0, "[[0,0]]", 0.05); _TestResult = _TestResult && doc_test_real_matrix(r1, "[[0,0]]", 0.05); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "nneighbor_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST odesolver_d1 // Solving y'=-y with ODE solver // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<13; _spoil_scenario++) { try { real_1d_array y = "[1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(y); if( _spoil_scenario==1 ) spoil_vector_by_posinf(y); if( _spoil_scenario==2 ) spoil_vector_by_neginf(y); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(y); real_1d_array x = "[0, 1, 2, 3]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(x); if( _spoil_scenario==5 ) spoil_vector_by_posinf(x); if( _spoil_scenario==6 ) spoil_vector_by_neginf(x); double eps = 0.00001; if( _spoil_scenario==7 ) eps = fp_nan; if( _spoil_scenario==8 ) eps = fp_posinf; if( _spoil_scenario==9 ) eps = fp_neginf; double h = 0; if( _spoil_scenario==10 ) h = fp_nan; if( _spoil_scenario==11 ) h = fp_posinf; if( _spoil_scenario==12 ) h = fp_neginf; odesolverstate s; ae_int_t m; real_1d_array xtbl; real_2d_array ytbl; odesolverreport rep; odesolverrkck(y, x, eps, h, s); alglib::odesolversolve(s, ode_function_1_diff); odesolverresults(s, m, xtbl, ytbl, rep); _TestResult = _TestResult && doc_test_int(m, 4); _TestResult = _TestResult && doc_test_real_vector(xtbl, "[0, 1, 2, 3]", 0.005); _TestResult = _TestResult && doc_test_real_matrix(ytbl, "[[1], [0.367], [0.135], [0.050]]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "odesolver_d1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST sparse_d_1 // Basic operations with sparse matrices // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<1; _spoil_scenario++) { try { // // This example demonstrates creation/initialization of the sparse matrix // and matrix-vector multiplication. // // First, we have to create matrix and initialize it. Matrix is initially created // in the Hash-Table format, which allows convenient initialization. We can modify // Hash-Table matrix with sparseset() and sparseadd() functions. // // NOTE: Unlike CRS format, Hash-Table representation allows you to initialize // elements in the arbitrary order. You may see that we initialize a[0][0] first, // then move to the second row, and then move back to the first row. // sparsematrix s; sparsecreate(2, 2, s); sparseset(s, 0, 0, 2.0); sparseset(s, 1, 1, 1.0); sparseset(s, 0, 1, 1.0); sparseadd(s, 1, 1, 4.0); // // Now S is equal to // [ 2 1 ] // [ 5 ] // Lets check it by reading matrix contents with sparseget(). // You may see that with sparseget() you may read both non-zero // and zero elements. // double v; v = sparseget(s, 0, 0); _TestResult = _TestResult && doc_test_real(v, 2.0000, 0.005); v = sparseget(s, 0, 1); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.005); v = sparseget(s, 1, 0); _TestResult = _TestResult && doc_test_real(v, 0.0000, 0.005); v = sparseget(s, 1, 1); _TestResult = _TestResult && doc_test_real(v, 5.0000, 0.005); // // After successful creation we can use our matrix for linear operations. // // However, there is one more thing we MUST do before using S in linear // operations: we have to convert it from HashTable representation (used for // initialization and dynamic operations) to CRS format with sparseconverttocrs() // call. If you omit this call, ALGLIB will generate exception on the first // attempt to use S in linear operations. // sparseconverttocrs(s); // // Now S is in the CRS format and we are ready to do linear operations. // Lets calculate A*x for some x. // real_1d_array x = "[1,-1]"; if( _spoil_scenario==0 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[]"; sparsemv(s, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[1.000,-5.000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "sparse_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST sparse_d_crs // Advanced topic: creation in the CRS format. // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<2; _spoil_scenario++) { try { // // This example demonstrates creation/initialization of the sparse matrix in the // CRS format. // // Hash-Table format used by default is very convenient (it allows easy // insertion of elements, automatic memory reallocation), but has // significant memory and performance overhead. Insertion of one element // costs hundreds of CPU cycles, and memory consumption is several times // higher than that of CRS. // // When you work with really large matrices and when you can tell in // advance how many elements EXACTLY you need, it can be beneficial to // create matrix in the CRS format from the very beginning. // // If you want to create matrix in the CRS format, you should: // * use sparsecreatecrs() function // * know row sizes in advance (number of non-zero entries in the each row) // * initialize matrix with sparseset() - another function, sparseadd(), is not allowed // * initialize elements from left to right, from top to bottom, each // element is initialized only once. // sparsematrix s; integer_1d_array row_sizes = "[2,2,2,1]"; if( _spoil_scenario==0 ) spoil_vector_by_deleting_element(row_sizes); sparsecreatecrs(4, 4, row_sizes, s); sparseset(s, 0, 0, 2.0); sparseset(s, 0, 1, 1.0); sparseset(s, 1, 1, 4.0); sparseset(s, 1, 2, 2.0); sparseset(s, 2, 2, 3.0); sparseset(s, 2, 3, 1.0); sparseset(s, 3, 3, 9.0); // // Now S is equal to // [ 2 1 ] // [ 4 2 ] // [ 3 1 ] // [ 9 ] // // We should point that we have initialized S elements from left to right, // from top to bottom. CRS representation does NOT allow you to do so in // the different order. Try to change order of the sparseset() calls above, // and you will see that your program generates exception. // // We can check it by reading matrix contents with sparseget(). // However, you should remember that sparseget() is inefficient on // CRS matrices (it may have to pass through all elements of the row // until it finds element you need). // double v; v = sparseget(s, 0, 0); _TestResult = _TestResult && doc_test_real(v, 2.0000, 0.005); v = sparseget(s, 2, 3); _TestResult = _TestResult && doc_test_real(v, 1.0000, 0.005); // you may see that you can read zero elements (which are not stored) with sparseget() v = sparseget(s, 3, 2); _TestResult = _TestResult && doc_test_real(v, 0.0000, 0.005); // // After successful creation we can use our matrix for linear operations. // Lets calculate A*x for some x. // real_1d_array x = "[1,-1,1,-1]"; if( _spoil_scenario==1 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[]"; sparsemv(s, x, y); _TestResult = _TestResult && doc_test_real_vector(y, "[1.000,-2.000,2.000,-9]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "sparse_d_crs"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ablas_d_gemm // Matrix multiplication (single-threaded) // _TestResult = true; try { real_2d_array a = "[[2,1],[1,3]]"; real_2d_array b = "[[2,1],[0,1]]"; real_2d_array c = "[[0,0],[0,0]]"; // // rmatrixgemm() function allows us to calculate matrix product C:=A*B or // to perform more general operation, C:=alpha*op1(A)*op2(B)+beta*C, // where A, B, C are rectangular matrices, op(X) can be X or X^T, // alpha and beta are scalars. // // This function: // * can apply transposition and/or multiplication by scalar to operands // * can use arbitrary part of matrices A/B (given by submatrix offset) // * can store result into arbitrary part of C // * for performance reasons requires C to be preallocated // // Parameters of this function are: // * M, N, K - sizes of op1(A) (which is MxK), op2(B) (which // is KxN) and C (which is MxN) // * Alpha - coefficient before A*B // * A, IA, JA - matrix A and offset of the submatrix // * OpTypeA - transformation type: // 0 - no transformation // 1 - transposition // * B, IB, JB - matrix B and offset of the submatrix // * OpTypeB - transformation type: // 0 - no transformation // 1 - transposition // * Beta - coefficient before C // * C, IC, JC - preallocated matrix C and offset of the submatrix // // Below we perform simple product C:=A*B (alpha=1, beta=0) // // IMPORTANT: this function works with preallocated C, which must be large // enough to store multiplication result. // ae_int_t m = 2; ae_int_t n = 2; ae_int_t k = 2; double alpha = 1.0; ae_int_t ia = 0; ae_int_t ja = 0; ae_int_t optypea = 0; ae_int_t ib = 0; ae_int_t jb = 0; ae_int_t optypeb = 0; double beta = 0.0; ae_int_t ic = 0; ae_int_t jc = 0; rmatrixgemm(m, n, k, alpha, a, ia, ja, optypea, b, ib, jb, optypeb, beta, c, ic, jc); _TestResult = _TestResult && doc_test_real_matrix(c, "[[4,3],[2,4]]", 0.0001); // // Now we try to apply some simple transformation to operands: C:=A*B^T // optypeb = 1; rmatrixgemm(m, n, k, alpha, a, ia, ja, optypea, b, ib, jb, optypeb, beta, c, ic, jc); _TestResult = _TestResult && doc_test_real_matrix(c, "[[5,1],[5,3]]", 0.0001); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "ablas_d_gemm"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ablas_d_syrk // Symmetric rank-K update (single-threaded) // _TestResult = true; try { // // rmatrixsyrk() function allows us to calculate symmetric rank-K update // C := beta*C + alpha*A'*A, where C is square N*N matrix, A is square K*N // matrix, alpha and beta are scalars. It is also possible to update by // adding A*A' instead of A'*A. // // Parameters of this function are: // * N, K - matrix size // * Alpha - coefficient before A // * A, IA, JA - matrix and submatrix offsets // * OpTypeA - multiplication type: // * 0 - A*A^T is calculated // * 2 - A^T*A is calculated // * Beta - coefficient before C // * C, IC, JC - preallocated input/output matrix and submatrix offsets // * IsUpper - whether upper or lower triangle of C is updated; // this function updates only one half of C, leaving // other half unchanged (not referenced at all). // // Below we will show how to calculate simple product C:=A'*A // // NOTE: beta=0 and we do not use previous value of C, but still it // MUST be preallocated. // ae_int_t n = 2; ae_int_t k = 1; double alpha = 1.0; ae_int_t ia = 0; ae_int_t ja = 0; ae_int_t optypea = 2; double beta = 0.0; ae_int_t ic = 0; ae_int_t jc = 0; bool isupper = true; real_2d_array a = "[[1,2]]"; // preallocate space to store result real_2d_array c = "[[0,0],[0,0]]"; // calculate product, store result into upper part of c rmatrixsyrk(n, k, alpha, a, ia, ja, optypea, beta, c, ic, jc, isupper); // output result. // IMPORTANT: lower triangle of C was NOT updated! _TestResult = _TestResult && doc_test_real_matrix(c, "[[1,2],[0,4]]", 0.0001); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "ablas_d_syrk"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ablas_t_complex // Basis test for complex matrix functions (correctness and presence of SMP support) // _TestResult = true; try { complex_2d_array a; complex_2d_array b; complex_2d_array c; // test cmatrixgemm() a = "[[2i,1i],[1,3]]"; b = "[[2,1],[0,1]]"; c = "[[0,0],[0,0]]"; cmatrixgemm(2, 2, 2, 1.0, a, 0, 0, 0, b, 0, 0, 0, 0.0, c, 0, 0); _TestResult = _TestResult && doc_test_complex_matrix(c, "[[4i,3i],[2,4]]", 0.0001); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "ablas_t_complex"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_r1 // Real matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { real_2d_array a = "[[1,-1],[1,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; rmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_matrix(a, "[[0.5,0.5],[-0.5,0.5]]", 0.00005); _TestResult = _TestResult && doc_test_real(rep.r1, 0.5, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.5, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_r1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_c1 // Complex matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { complex_2d_array a = "[[1i,-1],[1i,1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; cmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_complex_matrix(a, "[[-0.5i,-0.5i],[-0.5,0.5]]", 0.00005); _TestResult = _TestResult && doc_test_real(rep.r1, 0.5, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.5, 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_c1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_spd1 // SPD matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { real_2d_array a = "[[2,1],[1,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; spdmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_real_matrix(a, "[[0.666666,-0.333333],[-0.333333,0.666666]]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_spd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_d_hpd1 // HPD matrix inverse // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<7; _spoil_scenario++) { try { complex_2d_array a = "[[2,1],[1,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_adding_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_adding_col(a); if( _spoil_scenario==5 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==6 ) spoil_matrix_by_deleting_col(a); ae_int_t info; matinvreport rep; hpdmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, 1); _TestResult = _TestResult && doc_test_complex_matrix(a, "[[0.666666,-0.333333],[-0.333333,0.666666]]", 0.00005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_d_hpd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_t_r1 // Real matrix inverse: singular matrix // _TestResult = true; try { real_2d_array a = "[[1,-1],[-2,2]]"; ae_int_t info; matinvreport rep; rmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, -3); _TestResult = _TestResult && doc_test_real(rep.r1, 0.0, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.0, 0.00005); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_t_r1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_t_c1 // Complex matrix inverse: singular matrix // _TestResult = true; try { complex_2d_array a = "[[1i,-1i],[-2,2]]"; ae_int_t info; matinvreport rep; cmatrixinverse(a, info, rep); _TestResult = _TestResult && doc_test_int(info, -3); _TestResult = _TestResult && doc_test_real(rep.r1, 0.0, 0.00005); _TestResult = _TestResult && doc_test_real(rep.rinf, 0.0, 0.00005); } catch(ap_error) { _TestResult = false; } if( !_TestResult) { printf("%-32s FAILED\n", "matinv_t_c1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_e_spd1 // Attempt to use SPD function on nonsymmetrix matrix // _TestResult = true; try { real_2d_array a = "[[1,0],[1,1]]"; ae_int_t info; matinvreport rep; spdmatrixinverse(a, info, rep); _TestResult = false; } catch(ap_error) {} if( !_TestResult) { printf("%-32s FAILED\n", "matinv_e_spd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST matinv_e_hpd1 // Attempt to use SPD function on nonsymmetrix matrix // _TestResult = true; try { complex_2d_array a = "[[1,0],[1,1]]"; ae_int_t info; matinvreport rep; hpdmatrixinverse(a, info, rep); _TestResult = false; } catch(ap_error) {} if( !_TestResult) { printf("%-32s FAILED\n", "matinv_e_hpd1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlbfgs_d_1 // Nonlinear optimization by L-BFGS // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // using LBFGS method, with: // * initial point x=[0,0] // * unit scale being set for all variables (see minlbfgssetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; ae_int_t maxits = 0; minlbfgsstate state; minlbfgscreate(1, x, state); minlbfgssetcond(state, epsg, epsf, epsx, maxits); minlbfgssetscale(state, s); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minlbfgsoptguardsmoothness(state); minlbfgsoptguardgradient(state, 0.001); // // Optimize and examine results. // minlbfgsreport rep; alglib::minlbfgsoptimize(state, function1_grad); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minlbfgsoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlbfgs_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlbfgs_d_2 // Nonlinear optimization with additional settings and restarts // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4 // using LBFGS method. // // Several advanced techniques are demonstrated: // * upper limit on step size // * restart from new point // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; double stpmax = 0.1; if( _spoil_scenario==15 ) stpmax = fp_nan; if( _spoil_scenario==16 ) stpmax = fp_posinf; if( _spoil_scenario==17 ) stpmax = fp_neginf; ae_int_t maxits = 0; minlbfgsstate state; minlbfgsreport rep; // create and tune optimizer minlbfgscreate(1, x, state); minlbfgssetcond(state, epsg, epsf, epsx, maxits); minlbfgssetstpmax(state, stpmax); minlbfgssetscale(state, s); // Set up OptGuard integrity checker which catches errors // like nonsmooth targets or errors in the analytic gradient. // // OptGuard is essential at the early prototyping stages. // // NOTE: gradient verification needs 3*N additional function // evaluations; DO NOT USE IT IN THE PRODUCTION CODE // because it leads to unnecessary slowdown of your app. minlbfgsoptguardsmoothness(state); minlbfgsoptguardgradient(state, 0.001); // first run alglib::minlbfgsoptimize(state, function1_grad); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // second run - algorithm is restarted x = "[10,10]"; if( _spoil_scenario==18 ) spoil_vector_by_nan(x); if( _spoil_scenario==19 ) spoil_vector_by_posinf(x); if( _spoil_scenario==20 ) spoil_vector_by_neginf(x); minlbfgsrestartfrom(state, x); alglib::minlbfgsoptimize(state, function1_grad); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // check OptGuard integrity report. Why do we need it at all? // Well, try breaking the gradient by adding 1.0 to some // of its components - OptGuard should report it as error. // And it may also catch unintended errors too :) optguardreport ogrep; minlbfgsoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlbfgs_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlbfgs_numdiff // Nonlinear optimization by L-BFGS with numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4 // using numerical differentiation to calculate gradient. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsg = 0.0000000001; if( _spoil_scenario==3 ) epsg = fp_nan; if( _spoil_scenario==4 ) epsg = fp_posinf; if( _spoil_scenario==5 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==6 ) epsf = fp_nan; if( _spoil_scenario==7 ) epsf = fp_posinf; if( _spoil_scenario==8 ) epsf = fp_neginf; double epsx = 0; if( _spoil_scenario==9 ) epsx = fp_nan; if( _spoil_scenario==10 ) epsx = fp_posinf; if( _spoil_scenario==11 ) epsx = fp_neginf; double diffstep = 1.0e-6; if( _spoil_scenario==12 ) diffstep = fp_nan; if( _spoil_scenario==13 ) diffstep = fp_posinf; if( _spoil_scenario==14 ) diffstep = fp_neginf; ae_int_t maxits = 0; minlbfgsstate state; minlbfgsreport rep; minlbfgscreatef(1, x, diffstep, state); minlbfgssetcond(state, epsg, epsf, epsx, maxits); alglib::minlbfgsoptimize(state, function1_func); minlbfgsresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlbfgs_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST linlsqr_d_1 // Solution of sparse linear systems with CG // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<4; _spoil_scenario++) { try { // // This example illustrates solution of sparse linear least squares problem // with LSQR algorithm. // // Suppose that we have least squares problem min|A*x-b| with sparse A // represented by sparsematrix object // [ 1 1 ] // [ 1 1 ] // A = [ 2 1 ] // [ 1 ] // [ 1 ] // and right part b // [ 4 ] // [ 2 ] // b = [ 4 ] // [ 1 ] // [ 2 ] // and we want to solve this system in the least squares sense using // LSQR algorithm. In order to do so, we have to create left part // (sparsematrix object) and right part (dense array). // // Initially, sparse matrix is created in the Hash-Table format, // which allows easy initialization, but do not allow matrix to be // used in the linear solvers. So after construction you should convert // sparse matrix to CRS format (one suited for linear operations). // sparsematrix a; sparsecreate(5, 2, a); sparseset(a, 0, 0, 1.0); sparseset(a, 0, 1, 1.0); sparseset(a, 1, 0, 1.0); sparseset(a, 1, 1, 1.0); sparseset(a, 2, 0, 2.0); sparseset(a, 2, 1, 1.0); sparseset(a, 3, 0, 1.0); sparseset(a, 4, 1, 1.0); // // Now our matrix is fully initialized, but we have to do one more // step - convert it from Hash-Table format to CRS format (see // documentation on sparse matrices for more information about these // formats). // // If you omit this call, ALGLIB will generate exception on the first // attempt to use A in linear operations. // sparseconverttocrs(a); // // Initialization of the right part // real_1d_array b = "[4,2,4,1,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(b); if( _spoil_scenario==1 ) spoil_vector_by_posinf(b); if( _spoil_scenario==2 ) spoil_vector_by_neginf(b); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(b); // // Now we have to create linear solver object and to use it for the // solution of the linear system. // linlsqrstate s; linlsqrreport rep; real_1d_array x; linlsqrcreate(5, 2, s); linlsqrsolvesparse(s, a, b); linlsqrresults(s, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[1.000,2.000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "linlsqr_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbleic_d_1 // Nonlinear optimization with bound constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<20; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using BLEIC optimizer with: // * initial point x=[0,0] // * unit scale being set for all variables (see minbleicsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set box constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; minbleicstate state; minbleiccreate(x, state); minbleicsetbc(state, bndl, bndu); minbleicsetscale(state, s); minbleicsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minbleicoptguardsmoothness(state); minbleicoptguardgradient(state, 0.001); // // Optimize and evaluate results // minbleicreport rep; alglib::minbleicoptimize(state, function1_grad); minbleicresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minbleicoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbleic_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbleic_d_2 // Nonlinear optimization with linear inequality constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<22; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to inequality constraints // // * x>=2 (posed as general linear constraint), // * x+y>=6 // // using BLEIC optimizer with // * initial point x=[0,0] // * unit scale being set for all variables (see minbleicsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set linear constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[5,5]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_2d_array c = "[[1,0,2],[1,1,6]]"; if( _spoil_scenario==7 ) spoil_matrix_by_nan(c); if( _spoil_scenario==8 ) spoil_matrix_by_posinf(c); if( _spoil_scenario==9 ) spoil_matrix_by_neginf(c); if( _spoil_scenario==10 ) spoil_matrix_by_deleting_row(c); if( _spoil_scenario==11 ) spoil_matrix_by_deleting_col(c); integer_1d_array ct = "[1,1]"; if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(ct); minbleicstate state; double epsg = 0; if( _spoil_scenario==13 ) epsg = fp_nan; if( _spoil_scenario==14 ) epsg = fp_posinf; if( _spoil_scenario==15 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==16 ) epsf = fp_nan; if( _spoil_scenario==17 ) epsf = fp_posinf; if( _spoil_scenario==18 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==19 ) epsx = fp_nan; if( _spoil_scenario==20 ) epsx = fp_posinf; if( _spoil_scenario==21 ) epsx = fp_neginf; ae_int_t maxits = 0; minbleiccreate(x, state); minbleicsetlc(state, c, ct); minbleicsetscale(state, s); minbleicsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minbleicoptguardsmoothness(state); minbleicoptguardgradient(state, 0.001); // // Optimize and evaluate results // minbleicreport rep; alglib::minbleicoptimize(state, function1_grad); minbleicresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[2,4]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minbleicoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbleic_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbleic_numdiff // Nonlinear optimization with bound constraints and numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<23; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using BLEIC optimizer with: // * numerical differentiation being used // * initial point x=[0,0] // * unit scale being set for all variables (see minbleicsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set box constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); minbleicstate state; double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; double diffstep = 1.0e-6; if( _spoil_scenario==20 ) diffstep = fp_nan; if( _spoil_scenario==21 ) diffstep = fp_posinf; if( _spoil_scenario==22 ) diffstep = fp_neginf; minbleiccreatef(x, diffstep, state); minbleicsetbc(state, bndl, bndu); minbleicsetscale(state, s); minbleicsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // Numerical differentiation always produces "correct" gradient // (with some truncation error, but unbiased). Thus, we just have // to check smoothness properties of the target: C0 and C1 continuity. // // Sometimes user accidentally tries to solve nonsmooth problems // with smooth optimizer. OptGuard helps to detect such situations // early, at the prototyping stage. // minbleicoptguardsmoothness(state); // // Optimize and evaluate results // minbleicreport rep; alglib::minbleicoptimize(state, function1_func); minbleicresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // Want to challenge OptGuard? Try to make your problem // nonsmooth by replacing 100*(x+3)^4 by 100*|x+3| and // re-run optimizer. // optguardreport ogrep; minbleicoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbleic_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_u1 // Unconstrained dense quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<17; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1 // // Exact solution is [x0,x1] = [3,2] // // We provide algorithm with starting point, although in this case // (dense matrix, no constraints) it can work without such information. // // Several QP solvers are tried: QuickQP, BLEIC, DENSE-AUL. // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // real_2d_array a = "[[2,0],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array b = "[-6,-4]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(b); if( _spoil_scenario==6 ) spoil_vector_by_posinf(b); if( _spoil_scenario==7 ) spoil_vector_by_neginf(b); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(b); real_1d_array x0 = "[0,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(x0); if( _spoil_scenario==10 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==11 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(s); if( _spoil_scenario==14 ) spoil_vector_by_posinf(s); if( _spoil_scenario==15 ) spoil_vector_by_neginf(s); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(s); real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, b); minqpsetstartingpoint(state, x0); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with QuickQP solver. // // This solver is intended for medium and large-scale problems with box // constraints (general linear constraints are not supported), but it can // also be efficiently used on unconstrained problems. // // Default stopping criteria are used, Newton phase is active. // minqpsetalgoquickqp(state, 0.0, 0.0, 0.0, 0, true); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // Of course, unconstrained problems can be solved too. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_u1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_bc1 // Bound constrained dense quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1 // subject to bound constraints 0<=x0<=2.5, 0<=x1<=2.5 // // Exact solution is [x0,x1] = [2.5,2] // // We provide algorithm with starting point. With such small problem good starting // point is not really necessary, but with high-dimensional problem it can save us // a lot of time. // // Several QP solvers are tried: QuickQP, BLEIC, DENSE-AUL. // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // real_2d_array a = "[[2,0],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array b = "[-6,-4]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(b); if( _spoil_scenario==6 ) spoil_vector_by_posinf(b); if( _spoil_scenario==7 ) spoil_vector_by_neginf(b); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(b); real_1d_array x0 = "[0,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(x0); if( _spoil_scenario==10 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==11 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(s); if( _spoil_scenario==14 ) spoil_vector_by_posinf(s); if( _spoil_scenario==15 ) spoil_vector_by_neginf(s); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[0.0,0.0]"; if( _spoil_scenario==17 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==18 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[2.5,2.5]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(bndu); real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, b); minqpsetstartingpoint(state, x0); minqpsetbc(state, bndl, bndu); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with QuickQP solver. // // This solver is intended for medium and large-scale problems with box // constraints (general linear constraints are not supported). // // Default stopping criteria are used, Newton phase is active. // minqpsetalgoquickqp(state, 0.0, 0.0, 0.0, 0, true); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, 4); _TestResult = _TestResult && doc_test_real_vector(x, "[2.5,2]", 0.005); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2.5,2]", 0.005); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2.5,2]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_bc1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_lc1 // Linearly constrained dense quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<16; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1 // subject to linear constraint x0+x1<=2 // // Exact solution is [x0,x1] = [1.5,0.5] // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // real_2d_array a = "[[2,0],[0,2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array b = "[-6,-4]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(b); if( _spoil_scenario==6 ) spoil_vector_by_posinf(b); if( _spoil_scenario==7 ) spoil_vector_by_neginf(b); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(b); real_1d_array s = "[1,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(s); if( _spoil_scenario==10 ) spoil_vector_by_posinf(s); if( _spoil_scenario==11 ) spoil_vector_by_neginf(s); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(s); real_2d_array c = "[[1.0,1.0,2.0]]"; if( _spoil_scenario==13 ) spoil_matrix_by_nan(c); if( _spoil_scenario==14 ) spoil_matrix_by_posinf(c); if( _spoil_scenario==15 ) spoil_matrix_by_neginf(c); integer_1d_array ct = "[-1]"; real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetlinearterm(state, b); minqpsetlc(state, c, ct); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[1.500,0.500]", 0.05); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[1.500,0.500]", 0.05); // // Solve problem with QuickQP solver. // // This solver is intended for medium and large-scale problems with box // constraints, and... // // ...Oops! It does not support general linear constraints, -5 returned as completion code! // minqpsetalgoquickqp(state, 0.0, 0.0, 0.0, 0, true); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, -5); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_lc1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_u2 // Unconstrained sparse quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<12; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = x0^2 + x1^2 -6*x0 - 4*x1, // with quadratic term given by sparse matrix structure. // // Exact solution is [x0,x1] = [3,2] // // We provide algorithm with starting point, although in this case // (dense matrix, no constraints) it can work without such information. // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // // For example, our function is f(x)=x0^2+x1^2+..., but we rewrite it as // f(x) = 0.5*(2*x0^2+2*x1^2) + .... // and pass diag(2,2) as quadratic term - NOT diag(1,1)! // sparsematrix a; real_1d_array b = "[-6,-4]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(b); if( _spoil_scenario==1 ) spoil_vector_by_posinf(b); if( _spoil_scenario==2 ) spoil_vector_by_neginf(b); if( _spoil_scenario==3 ) spoil_vector_by_deleting_element(b); real_1d_array x0 = "[0,1]"; if( _spoil_scenario==4 ) spoil_vector_by_nan(x0); if( _spoil_scenario==5 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==6 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(s); if( _spoil_scenario==9 ) spoil_vector_by_posinf(s); if( _spoil_scenario==10 ) spoil_vector_by_neginf(s); if( _spoil_scenario==11 ) spoil_vector_by_deleting_element(s); real_1d_array x; minqpstate state; minqpreport rep; // initialize sparsematrix structure sparsecreate(2, 2, 0, a); sparseset(a, 0, 0, 2.0); sparseset(a, 1, 1, 2.0); // create solver, set quadratic/linear terms minqpcreate(2, state); minqpsetquadratictermsparse(state, a, true); minqpsetlinearterm(state, b); minqpsetstartingpoint(state, x0); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: for convex problems you may try using minqpsetscaleautodiag() // which automatically determines variable scales. minqpsetscale(state, s); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // It also supports sparse problems. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[3,2]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_u2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minqp_d_nonconvex // Nonconvex quadratic programming // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of nonconvex function // F(x0,x1) = -(x0^2+x1^2) // subject to constraints x0,x1 in [1.0,2.0] // Exact solution is [x0,x1] = [2,2]. // // Non-convex problems are harded to solve than convex ones, and they // may have more than one local minimum. However, ALGLIB solves may deal // with such problems (altough they do not guarantee convergence to // global minimum). // // IMPORTANT: this solver minimizes following function: // f(x) = 0.5*x'*A*x + b'*x. // Note that quadratic term has 0.5 before it. So if you want to minimize // quadratic function, you should rewrite it in such way that quadratic term // is multiplied by 0.5 too. // // For example, our function is f(x)=-(x0^2+x1^2), but we rewrite it as // f(x) = 0.5*(-2*x0^2-2*x1^2) // and pass diag(-2,-2) as quadratic term - NOT diag(-1,-1)! // real_2d_array a = "[[-2,0],[0,-2]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(a); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(a); if( _spoil_scenario==3 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==4 ) spoil_matrix_by_deleting_col(a); real_1d_array x0 = "[1,1]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(x0); if( _spoil_scenario==6 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==7 ) spoil_vector_by_neginf(x0); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(s); if( _spoil_scenario==10 ) spoil_vector_by_posinf(s); if( _spoil_scenario==11 ) spoil_vector_by_neginf(s); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[1.0,1.0]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[2.0,2.0]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==16 ) spoil_vector_by_deleting_element(bndu); real_1d_array x; minqpstate state; minqpreport rep; // create solver, set quadratic/linear terms, constraints minqpcreate(2, state); minqpsetquadraticterm(state, a); minqpsetstartingpoint(state, x0); minqpsetbc(state, bndl, bndu); // Set scale of the parameters. // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // // NOTE: there also exists minqpsetscaleautodiag() function // which automatically determines variable scales; however, // it does NOT work for non-convex problems. minqpsetscale(state, s); // // Solve problem with BLEIC-based QP solver. // // This solver is intended for problems with moderate (up to 50) number // of general linear constraints and unlimited number of box constraints. // // It may solve non-convex problems as long as they are bounded from // below under constraints. // // Default stopping criteria are used. // minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2,2]", 0.005); // // Solve problem with DENSE-AUL solver. // // This solver is optimized for problems with up to several thousands of // variables and large amount of general linear constraints. Problems with // less than 50 general linear constraints can be efficiently solved with // BLEIC, problems with box-only constraints can be solved with QuickQP. // However, DENSE-AUL will work in any (including unconstrained) case. // // Algorithm convergence is guaranteed only for convex case, but you may // expect that it will work for non-convex problems too (because near the // solution they are locally convex). // // Default stopping criteria are used. // minqpsetalgodenseaul(state, 1.0e-9, 1.0e+4, 5); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[2,2]", 0.005); // Hmm... this problem is bounded from below (has solution) only under constraints. // What it we remove them? // // You may see that BLEIC algorithm detects unboundedness of the problem, // -4 is returned as completion code. However, DENSE-AUL is unable to detect // such situation and it will cycle forever (we do not test it here). real_1d_array nobndl = "[-inf,-inf]"; if( _spoil_scenario==17 ) spoil_vector_by_nan(nobndl); if( _spoil_scenario==18 ) spoil_vector_by_deleting_element(nobndl); real_1d_array nobndu = "[+inf,+inf]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(nobndu); if( _spoil_scenario==20 ) spoil_vector_by_deleting_element(nobndu); minqpsetbc(state, nobndl, nobndu); minqpsetalgobleic(state, 0.0, 0.0, 0.0, 0); minqpoptimize(state); minqpresults(state, x, rep); _TestResult = _TestResult && doc_test_int(rep.terminationtype, -4); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minqp_d_nonconvex"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlp_basic // Basic linear programming example // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates how to minimize // // F(x0,x1) = -0.1*x0 - x1 // // subject to box constraints // // -1 <= x0,x1 <= +1 // // and general linear constraints // // x0 - x1 >= -1 // x0 + x1 <= 1 // // We use dual simplex solver provided by ALGLIB for this task. Box // constraints are specified by means of constraint vectors bndl and // bndu (we have bndl<=x<=bndu). General linear constraints are // specified as AL<=A*x<=AU, with AL/AU being 2x1 vectors and A being // 2x2 matrix. // // NOTE: some/all components of AL/AU can be +-INF, same applies to // bndl/bndu. You can also have AL[I]=AU[i] (as well as // BndL[i]=BndU[i]). // real_2d_array a = "[[1,-1],[1,+1]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(a); if( _spoil_scenario==1 ) spoil_matrix_by_deleting_row(a); if( _spoil_scenario==2 ) spoil_matrix_by_deleting_col(a); real_1d_array al = "[-1,-inf]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(al); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(al); real_1d_array au = "[+inf,+1]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(au); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(au); real_1d_array c = "[-0.1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(c); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(c); real_1d_array s = "[1,1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(s); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==11 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==12 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==13 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(bndu); real_1d_array x; minlpstate state; minlpreport rep; minlpcreate(2, state); // // Set cost vector, box constraints, general linear constraints. // // Box constraints can be set in one call to minlpsetbc() or minlpsetbcall() // (latter sets same constraints for all variables and accepts two scalars // instead of two vectors). // // General linear constraints can be specified in several ways: // * minlpsetlc2dense() - accepts dense 2D array as input; sometimes this // approach is more convenient, although less memory-efficient. // * minlpsetlc2() - accepts sparse matrix as input // * minlpaddlc2dense() - appends one row to the current set of constraints; // row being appended is specified as dense vector // * minlpaddlc2() - appends one row to the current set of constraints; // row being appended is specified as sparse set of elements // Independently from specific function being used, LP solver uses sparse // storage format for internal representation of constraints. // minlpsetcost(state, c); minlpsetbc(state, bndl, bndu); minlpsetlc2dense(state, a, al, au, 2); // // Set scale of the parameters. // // It is strongly recommended that you set scale of your variables. // Knowing their scales is essential for evaluation of stopping criteria // and for preconditioning of the algorithm steps. // You can find more information on scaling at http://www.alglib.net/optimization/scaling.php // minlpsetscale(state, s); // Solve minlpoptimize(state); minlpresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[0,1]", 0.0005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlp_basic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minnlc_d_inequality // Nonlinearly constrained optimization (inequality constraints) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = -x0+x1 // // subject to box constraints // // x0>=0, x1>=0 // // and nonlinear inequality constraint // // x0^2 + x1^2 - 1 <= 0 // real_1d_array x0 = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; real_1d_array bndl = "[0,0]"; real_1d_array bndu = "[+inf,+inf]"; minnlcstate state; // // Create optimizer object and tune its settings: // * epsx=0.000001 stopping condition for inner iterations // * s=[1,1] all variables have unit scale; it is important to // tell optimizer about scales of your variables - it // greatly accelerates convergence and helps to perform // some important integrity checks. // minnlccreate(2, x0, state); minnlcsetcond(state, epsx, maxits); minnlcsetscale(state, s); // // Choose one of the nonlinear programming solvers supported by minnlc // optimizer: // * SQP - sequential quadratic programming NLP solver // * AUL - augmented Lagrangian NLP solver // * SLP - successive linear programming NLP solver // // Different solvers have different properties: // * SQP needs less function evaluations than any other solver, but it // has much higher iteration cost than other solvers (a QP subproblem // has to be solved during each step) // * AUL solver has cheaper iterations, but needs more target function // evaluations // * SLP is the most robust solver provided by ALGLIB, but it performs // order of magnitude more iterations than SQP. // // In the code below we set solver to be AUL but then override it with SLP, // and then with SQP, so the effective choice is to use SLP. We recommend // you to use SQP at least for early prototyping stages, and then switch // to AUL if possible. // double rho = 1000.0; ae_int_t outerits = 5; minnlcsetalgoaul(state, rho, outerits); minnlcsetalgoslp(state); minnlcsetalgosqp(state); // // Set constraints: // // 1. boundary constraints are passed with minnlcsetbc() call // // 2. nonlinear constraints are more tricky - you can not "pack" general // nonlinear function into double precision array. That's why // minnlcsetnlc() does not accept constraints itself - only constraint // counts are passed: first parameter is number of equality constraints, // second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNLC optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with general linear constraints, but you can // easily find it in documentation on minnlcsetlc() function. // minnlcsetbc(state, bndl, bndu); minnlcsetnlc(state, 0, 1); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target/constraints (C0 continuity violation) // * nonsmoothness of the target/constraints (C1 continuity violation) // * erroneous analytic Jacobian, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minnlcoptguardsmoothness(state); minnlcoptguardgradient(state, 0.001); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints. // // So, our vector function has form // // {f0,f1} = { -x0+x1 , x0^2+x1^2-1 } // // with Jacobian // // [ -1 +1 ] // J = [ ] // [ 2*x0 2*x1 ] // // with f0 being target function, f1 being constraining function. Number // of equality/inequality constraints is specified by minnlcsetnlc(), // with equality ones always being first, inequality ones being last. // minnlcreport rep; real_1d_array x1; alglib::minnlcoptimize(state, nlcfunc1_jac); minnlcresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[1.0000,0.0000]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // optguardreport ogrep; minnlcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minnlc_d_inequality"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minnlc_d_equality // Nonlinearly constrained optimization (equality constraints) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = -x0+x1 // // subject to nonlinear equality constraint // // x0^2 + x1^2 - 1 = 0 // real_1d_array x0 = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minnlcstate state; // // Create optimizer object and tune its settings: // * epsx=0.000001 stopping condition for inner iterations // * s=[1,1] all variables have unit scale // minnlccreate(2, x0, state); minnlcsetcond(state, epsx, maxits); minnlcsetscale(state, s); // // Choose one of the nonlinear programming solvers supported by minnlc // optimizer: // * SLP - successive linear programming NLP solver // * AUL - augmented Lagrangian NLP solver // // Different solvers have different properties: // * SLP is the most robust solver provided by ALGLIB: it can solve both // convex and nonconvex optimization problems, it respects box and // linear constraints (after you find feasible point it won't move away // from the feasible area) and tries to respect nonlinear constraints // as much as possible. It also usually needs less function evaluations // to converge than AUL. // However, it solves LP subproblems at each iterations which adds // significant overhead to its running time. Sometimes it can be as much // as 7x times slower than AUL. // * AUL solver is less robust than SLP - it can violate box and linear // constraints at any moment, and it is intended for convex optimization // problems (although in many cases it can deal with nonconvex ones too). // Also, unlike SLP it needs some tuning (penalty factor and number of // outer iterations). // However, it is often much faster than the current version of SLP. // // In the code below we set solver to be AUL but then override it with SLP, // so the effective choice is to use SLP. We recommend you to use SLP at // least for early prototyping stages. // // You can comment out line with SLP if you want to solve your problem with // AUL solver. // double rho = 1000.0; ae_int_t outerits = 5; minnlcsetalgoaul(state, rho, outerits); minnlcsetalgoslp(state); // // Set constraints: // // Nonlinear constraints are tricky - you can not "pack" general // nonlinear function into double precision array. That's why // minnlcsetnlc() does not accept constraints itself - only constraint // counts are passed: first parameter is number of equality constraints, // second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNLC optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with general linear constraints, but you can // easily find it in documentation on minnlcsetbc() and // minnlcsetlc() functions. // minnlcsetnlc(state, 1, 0); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target/constraints (C0 continuity violation) // * nonsmoothness of the target/constraints (C1 continuity violation) // * erroneous analytic Jacobian, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minnlcoptguardsmoothness(state); minnlcoptguardgradient(state, 0.001); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints. // // So, our vector function has form // // {f0,f1} = { -x0+x1 , x0^2+x1^2-1 } // // with Jacobian // // [ -1 +1 ] // J = [ ] // [ 2*x0 2*x1 ] // // with f0 being target function, f1 being constraining function. Number // of equality/inequality constraints is specified by minnlcsetnlc(), // with equality ones always being first, inequality ones being last. // minnlcreport rep; real_1d_array x1; alglib::minnlcoptimize(state, nlcfunc1_jac); minnlcresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[0.70710,-0.70710]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // optguardreport ogrep; minnlcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minnlc_d_equality"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minnlc_d_mixed // Nonlinearly constrained optimization with mixed equality/inequality constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = x0+x1 // // subject to nonlinear inequality constraint // // x0^2 + x1^2 - 1 <= 0 // // and nonlinear equality constraint // // x2-exp(x0) = 0 // real_1d_array x0 = "[0,0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minnlcstate state; minnlcreport rep; real_1d_array x1; // // Create optimizer object and tune its settings: // * epsx=0.000001 stopping condition for inner iterations // * s=[1,1] all variables have unit scale // * upper limit on step length is specified (to avoid probing locations where exp() is large) // minnlccreate(3, x0, state); minnlcsetcond(state, epsx, maxits); minnlcsetscale(state, s); minnlcsetstpmax(state, 10.0); // // Choose one of the nonlinear programming solvers supported by minnlc // optimizer: // * SLP - successive linear programming NLP solver // * AUL - augmented Lagrangian NLP solver // // Different solvers have different properties: // * SLP is the most robust solver provided by ALGLIB: it can solve both // convex and nonconvex optimization problems, it respects box and // linear constraints (after you find feasible point it won't move away // from the feasible area) and tries to respect nonlinear constraints // as much as possible. It also usually needs less function evaluations // to converge than AUL. // However, it solves LP subproblems at each iterations which adds // significant overhead to its running time. Sometimes it can be as much // as 7x times slower than AUL. // * AUL solver is less robust than SLP - it can violate box and linear // constraints at any moment, and it is intended for convex optimization // problems (although in many cases it can deal with nonconvex ones too). // Also, unlike SLP it needs some tuning (penalty factor and number of // outer iterations). // However, it is often much faster than the current version of SLP. // // In the code below we set solver to be AUL but then override it with SLP, // so the effective choice is to use SLP. We recommend you to use SLP at // least for early prototyping stages. // // You can comment out line with SLP if you want to solve your problem with // AUL solver. // double rho = 1000.0; ae_int_t outerits = 5; minnlcsetalgoaul(state, rho, outerits); minnlcsetalgoslp(state); // // Set constraints: // // Nonlinear constraints are tricky - you can not "pack" general // nonlinear function into double precision array. That's why // minnlcsetnlc() does not accept constraints itself - only constraint // counts are passed: first parameter is number of equality constraints, // second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNLC optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with boundary or general linear constraints, but you // can easily find it in documentation on minnlcsetbc() and // minnlcsetlc() functions. // minnlcsetnlc(state, 1, 1); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target/constraints (C0 continuity violation) // * nonsmoothness of the target/constraints (C1 continuity violation) // * erroneous analytic Jacobian, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minnlcoptguardsmoothness(state); minnlcoptguardgradient(state, 0.001); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints. // // So, our vector function has form // // {f0,f1,f2} = { x0+x1 , x2-exp(x0) , x0^2+x1^2-1 } // // with Jacobian // // [ +1 +1 0 ] // J = [-exp(x0) 0 1 ] // [ 2*x0 2*x1 0 ] // // with f0 being target function, f1 being equality constraint "f1=0", // f2 being inequality constraint "f2<=0". Number of equality/inequality // constraints is specified by minnlcsetnlc(), with equality ones always // being first, inequality ones being last. // alglib::minnlcoptimize(state, nlcfunc2_jac); minnlcresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[-0.70710,-0.70710,0.49306]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // optguardreport ogrep; minnlcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minnlc_d_mixed"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbc_d_1 // Nonlinear optimization with box constraints // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<20; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using MinBC optimizer with: // * initial point x=[0,0] // * unit scale being set for all variables (see minbcsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties: // * set box constraints // * set variable scales // * set stopping criteria // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); minbcstate state; double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; minbccreate(x, state); minbcsetbc(state, bndl, bndu); minbcsetscale(state, s); minbcsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // minbcoptguardsmoothness(state); minbcoptguardgradient(state, 0.001); // // Optimize and evaluate results // minbcreport rep; alglib::minbcoptimize(state, function1_grad); minbcresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; minbcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbc_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minbc_numdiff // Nonlinear optimization with bound constraints and numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<23; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // subject to box constraints // // -1<=x<=+1, -1<=y<=+1 // // using MinBC optimizer with: // * numerical differentiation being used // * initial point x=[0,0] // * unit scale being set for all variables (see minbcsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); if( _spoil_scenario==6 ) spoil_vector_by_deleting_element(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==8 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==10 ) spoil_vector_by_deleting_element(bndu); minbcstate state; double epsg = 0; if( _spoil_scenario==11 ) epsg = fp_nan; if( _spoil_scenario==12 ) epsg = fp_posinf; if( _spoil_scenario==13 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==14 ) epsf = fp_nan; if( _spoil_scenario==15 ) epsf = fp_posinf; if( _spoil_scenario==16 ) epsf = fp_neginf; double epsx = 0.000001; if( _spoil_scenario==17 ) epsx = fp_nan; if( _spoil_scenario==18 ) epsx = fp_posinf; if( _spoil_scenario==19 ) epsx = fp_neginf; ae_int_t maxits = 0; double diffstep = 1.0e-6; if( _spoil_scenario==20 ) diffstep = fp_nan; if( _spoil_scenario==21 ) diffstep = fp_posinf; if( _spoil_scenario==22 ) diffstep = fp_neginf; // // Now we are ready to actually optimize something: // * first we create optimizer // * we add boundary constraints // * we tune stopping conditions // * and, finally, optimize and obtain results... // minbccreatef(x, diffstep, state); minbcsetbc(state, bndl, bndu); minbcsetscale(state, s); minbcsetcond(state, epsg, epsf, epsx, maxits); // // Then we activate OptGuard integrity checking. // // Numerical differentiation always produces "correct" gradient // (with some truncation error, but unbiased). Thus, we just have // to check smoothness properties of the target: C0 and C1 continuity. // // Sometimes user accidentally tries to solve nonsmooth problems // with smooth optimizer. OptGuard helps to detect such situations // early, at the prototyping stage. // minbcoptguardsmoothness(state); // // Optimize and evaluate results // minbcreport rep; alglib::minbcoptimize(state, function1_func); minbcresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,1]", 0.005); // // Check that OptGuard did not report errors // // Want to challenge OptGuard? Try to make your problem // nonsmooth by replacing 100*(x+3)^4 by 100*|x+3| and // re-run optimizer. // optguardreport ogrep; minbcoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minbc_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_unconstrained // Nonsmooth unconstrained optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // using nonsmooth nonlinear optimizer. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.00001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; double radius = 0.1; if( _spoil_scenario==9 ) radius = fp_nan; if( _spoil_scenario==10 ) radius = fp_posinf; if( _spoil_scenario==11 ) radius = fp_neginf; double rho = 0.0; if( _spoil_scenario==12 ) rho = fp_nan; if( _spoil_scenario==13 ) rho = fp_posinf; if( _spoil_scenario==14 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=0.0 penalty coefficient for nonlinear constraints; can be zero // because we do not have such constraints // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreate(2, x0, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints // (box/linear ones are passed separately by means of minnssetbc() and // minnssetlc() calls). // // If you do not have nonlinear constraints (exactly our situation), then // you will have one-component function vector and 1xN Jacobian matrix. // // So, our vector function has form // // {f0} = { 2*|x0|+|x1| } // // with Jacobian // // [ ] // J = [ 2*sign(x0) sign(x1) ] // [ ] // // NOTE: nonsmooth optimizer requires considerably more function // evaluations than smooth solver - about 2N times more. Using // numerical differentiation introduces additional (multiplicative) // 2N speedup. // // It means that if smooth optimizer WITH user-supplied gradient // needs 100 function evaluations to solve 50-dimensional problem, // then AGS solver with user-supplied gradient will need about 10.000 // function evaluations, and with numerical gradient about 1.000.000 // function evaluations will be performed. // // NOTE: AGS solver used by us can handle nonsmooth and nonconvex // optimization problems. It has convergence guarantees, i.e. it will // converge to stationary point of the function after running for some // time. // // However, it is important to remember that "stationary point" is not // equal to "solution". If your problem is convex, everything is OK. // But nonconvex optimization problems may have "flat spots" - large // areas where gradient is exactly zero, but function value is far away // from optimal. Such areas are stationary points too, and optimizer // may be trapped here. // // "Flat spots" are nonsmooth equivalent of the saddle points, but with // orders of magnitude worse properties - they may be quite large and // hard to avoid. All nonsmooth optimizers are prone to this kind of the // problem, because it is impossible to automatically distinguish "flat // spot" from true solution. // // This note is here to warn you that you should be very careful when // you solve nonsmooth optimization problems. Visual inspection of // results is essential. // alglib::minnsoptimize(state, nsfunc1_jac); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[0.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_unconstrained"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_diff // Nonsmooth unconstrained optimization with numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<18; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // using nonsmooth nonlinear optimizer with numerical // differentiation provided by ALGLIB. // // NOTE: nonsmooth optimizer requires considerably more function // evaluations than smooth solver - about 2N times more. Using // numerical differentiation introduces additional (multiplicative) // 2N speedup. // // It means that if smooth optimizer WITH user-supplied gradient // needs 100 function evaluations to solve 50-dimensional problem, // then AGS solver with user-supplied gradient will need about 10.000 // function evaluations, and with numerical gradient about 1.000.000 // function evaluations will be performed. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.00001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; double diffstep = 0.000001; if( _spoil_scenario==9 ) diffstep = fp_nan; if( _spoil_scenario==10 ) diffstep = fp_posinf; if( _spoil_scenario==11 ) diffstep = fp_neginf; double radius = 0.1; if( _spoil_scenario==12 ) radius = fp_nan; if( _spoil_scenario==13 ) radius = fp_posinf; if( _spoil_scenario==14 ) radius = fp_neginf; double rho = 0.0; if( _spoil_scenario==15 ) rho = fp_nan; if( _spoil_scenario==16 ) rho = fp_posinf; if( _spoil_scenario==17 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=0.0 penalty coefficient for nonlinear constraints; can be zero // because we do not have such constraints // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreatef(2, x0, diffstep, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Optimize and test results. // // Optimizer object accepts vector function, with first component // being target function, and next components being nonlinear equality // and inequality constraints (box/linear ones are passed separately // by means of minnssetbc() and minnssetlc() calls). // // If you do not have nonlinear constraints (exactly our situation), then // you will have one-component function vector. // // So, our vector function has form // // {f0} = { 2*|x0|+|x1| } // alglib::minnsoptimize(state, nsfunc1_fvec); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[0.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_diff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_bc // Nonsmooth box constrained optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<17; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // subject to box constraints // // 1 <= x0 < +INF // -INF <= x1 < +INF // // using nonsmooth nonlinear optimizer. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); real_1d_array bndl = "[1,-inf]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(bndl); real_1d_array bndu = "[+inf,+inf]"; if( _spoil_scenario==7 ) spoil_vector_by_nan(bndu); double epsx = 0.00001; if( _spoil_scenario==8 ) epsx = fp_nan; if( _spoil_scenario==9 ) epsx = fp_posinf; if( _spoil_scenario==10 ) epsx = fp_neginf; double radius = 0.1; if( _spoil_scenario==11 ) radius = fp_nan; if( _spoil_scenario==12 ) radius = fp_posinf; if( _spoil_scenario==13 ) radius = fp_neginf; double rho = 0.0; if( _spoil_scenario==14 ) rho = fp_nan; if( _spoil_scenario==15 ) rho = fp_posinf; if( _spoil_scenario==16 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=0.0 penalty coefficient for nonlinear constraints; can be zero // because we do not have such constraints // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreate(2, x0, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Set box constraints. // // General linear constraints are set in similar way (see comments on // minnssetlc() function for more information). // // You may combine box, linear and nonlinear constraints in one optimization // problem. // minnssetbc(state, bndl, bndu); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints // (box/linear ones are passed separately by means of minnssetbc() and // minnssetlc() calls). // // If you do not have nonlinear constraints (exactly our situation), then // you will have one-component function vector and 1xN Jacobian matrix. // // So, our vector function has form // // {f0} = { 2*|x0|+|x1| } // // with Jacobian // // [ ] // J = [ 2*sign(x0) sign(x1) ] // [ ] // // NOTE: nonsmooth optimizer requires considerably more function // evaluations than smooth solver - about 2N times more. Using // numerical differentiation introduces additional (multiplicative) // 2N speedup. // // It means that if smooth optimizer WITH user-supplied gradient // needs 100 function evaluations to solve 50-dimensional problem, // then AGS solver with user-supplied gradient will need about 10.000 // function evaluations, and with numerical gradient about 1.000.000 // function evaluations will be performed. // // NOTE: AGS solver used by us can handle nonsmooth and nonconvex // optimization problems. It has convergence guarantees, i.e. it will // converge to stationary point of the function after running for some // time. // // However, it is important to remember that "stationary point" is not // equal to "solution". If your problem is convex, everything is OK. // But nonconvex optimization problems may have "flat spots" - large // areas where gradient is exactly zero, but function value is far away // from optimal. Such areas are stationary points too, and optimizer // may be trapped here. // // "Flat spots" are nonsmooth equivalent of the saddle points, but with // orders of magnitude worse properties - they may be quite large and // hard to avoid. All nonsmooth optimizers are prone to this kind of the // problem, because it is impossible to automatically distinguish "flat // spot" from true solution. // // This note is here to warn you that you should be very careful when // you solve nonsmooth optimization problems. Visual inspection of // results is essential. // // alglib::minnsoptimize(state, nsfunc1_jac); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[1.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_bc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minns_d_nlc // Nonsmooth nonlinearly constrained optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x0,x1) = 2*|x0|+|x1| // // subject to combination of equality and inequality constraints // // x0 = 1 // x1 >= -1 // // using nonsmooth nonlinear optimizer. Although these constraints // are linear, we treat them as general nonlinear ones in order to // demonstrate nonlinearly constrained optimization setup. // real_1d_array x0 = "[1,1]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x0); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x0); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x0); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.00001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; double radius = 0.1; if( _spoil_scenario==9 ) radius = fp_nan; if( _spoil_scenario==10 ) radius = fp_posinf; if( _spoil_scenario==11 ) radius = fp_neginf; double rho = 50.0; if( _spoil_scenario==12 ) rho = fp_nan; if( _spoil_scenario==13 ) rho = fp_posinf; if( _spoil_scenario==14 ) rho = fp_neginf; ae_int_t maxits = 0; minnsstate state; minnsreport rep; real_1d_array x1; // // Create optimizer object, choose AGS algorithm and tune its settings: // * radius=0.1 good initial value; will be automatically decreased later. // * rho=50.0 penalty coefficient for nonlinear constraints. It is your // responsibility to choose good one - large enough that it // enforces constraints, but small enough in order to avoid // extreme slowdown due to ill-conditioning. // * epsx=0.000001 stopping conditions // * s=[1,1] all variables have unit scale // minnscreate(2, x0, state); minnssetalgoags(state, radius, rho); minnssetcond(state, epsx, maxits); minnssetscale(state, s); // // Set general nonlinear constraints. // // This part is more tricky than working with box/linear constraints - you // can not "pack" general nonlinear function into double precision array. // That's why minnssetnlc() does not accept constraints itself - only // constraint COUNTS are passed: first parameter is number of equality // constraints, second one is number of inequality constraints. // // As for constraining functions - these functions are passed as part // of problem Jacobian (see below). // // NOTE: MinNS optimizer supports arbitrary combination of boundary, general // linear and general nonlinear constraints. This example does not // show how to work with general linear constraints, but you can // easily find it in documentation on minnlcsetlc() function. // minnssetnlc(state, 1, 1); // // Optimize and test results. // // Optimizer object accepts vector function and its Jacobian, with first // component (Jacobian row) being target function, and next components // (Jacobian rows) being nonlinear equality and inequality constraints // (box/linear ones are passed separately by means of minnssetbc() and // minnssetlc() calls). // // Nonlinear equality constraints have form Gi(x)=0, inequality ones // have form Hi(x)<=0, so we may have to "normalize" constraints prior // to passing them to optimizer (right side is zero, constraints are // sorted, multiplied by -1 when needed). // // So, our vector function has form // // {f0,f1,f2} = { 2*|x0|+|x1|, x0-1, -x1-1 } // // with Jacobian // // [ 2*sign(x0) sign(x1) ] // J = [ 1 0 ] // [ 0 -1 ] // // which means that we have optimization problem // // min{f0} subject to f1=0, f2<=0 // // which is essentially same as // // min { 2*|x0|+|x1| } subject to x0=1, x1>=-1 // // NOTE: AGS solver used by us can handle nonsmooth and nonconvex // optimization problems. It has convergence guarantees, i.e. it will // converge to stationary point of the function after running for some // time. // // However, it is important to remember that "stationary point" is not // equal to "solution". If your problem is convex, everything is OK. // But nonconvex optimization problems may have "flat spots" - large // areas where gradient is exactly zero, but function value is far away // from optimal. Such areas are stationary points too, and optimizer // may be trapped here. // // "Flat spots" are nonsmooth equivalent of the saddle points, but with // orders of magnitude worse properties - they may be quite large and // hard to avoid. All nonsmooth optimizers are prone to this kind of the // problem, because it is impossible to automatically distinguish "flat // spot" from true solution. // // This note is here to warn you that you should be very careful when // you solve nonsmooth optimization problems. Visual inspection of // results is essential. // alglib::minnsoptimize(state, nsfunc2_jac); minnsresults(state, x1, rep); _TestResult = _TestResult && doc_test_real_vector(x1, "[1.0000,0.0000]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minns_d_nlc"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mincg_d_1 // Nonlinear optimization by CG // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<15; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // using nonlinear conjugate gradient method with: // * initial point x=[0,0] // * unit scale being set for all variables (see mincgsetscale for more info) // * stopping criteria set to "terminate after short enough step" // * OptGuard integrity check being used to check problem statement // for some common errors like nonsmoothness or bad analytic gradient // // First, we create optimizer object and tune its properties // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; ae_int_t maxits = 0; mincgstate state; mincgcreate(x, state); mincgsetcond(state, epsg, epsf, epsx, maxits); mincgsetscale(state, s); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to catch common coding and problem statement // issues, like: // * discontinuity of the target function (C0 continuity violation) // * nonsmoothness of the target function (C1 continuity violation) // * erroneous analytic gradient, i.e. one inconsistent with actual // change in the target/constraints // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: GRADIENT VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION. DO NOT USE IT IN PRODUCTION CODE!!!!!!! // // Other OptGuard checks add moderate overhead, but anyway // it is better to turn them off when they are not needed. // mincgoptguardsmoothness(state); mincgoptguardgradient(state, 0.001); // // Optimize and evaluate results // mincgreport rep; alglib::mincgoptimize(state, function1_grad); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the gradient - say, add // 1.0 to some of its components. // optguardreport ogrep; mincgoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mincg_d_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mincg_d_2 // Nonlinear optimization with additional settings and restarts // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<21; _spoil_scenario++) { try { // // This example demonstrates minimization of f(x,y) = 100*(x+3)^4+(y-3)^4 // with nonlinear conjugate gradient method. // // Several advanced techniques are demonstrated: // * upper limit on step size // * restart from new point // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; double stpmax = 0.1; if( _spoil_scenario==15 ) stpmax = fp_nan; if( _spoil_scenario==16 ) stpmax = fp_posinf; if( _spoil_scenario==17 ) stpmax = fp_neginf; ae_int_t maxits = 0; mincgstate state; mincgreport rep; // create and tune optimizer mincgcreate(x, state); mincgsetscale(state, s); mincgsetcond(state, epsg, epsf, epsx, maxits); mincgsetstpmax(state, stpmax); // Set up OptGuard integrity checker which catches errors // like nonsmooth targets or errors in the analytic gradient. // // OptGuard is essential at the early prototyping stages. // // NOTE: gradient verification needs 3*N additional function // evaluations; DO NOT USE IT IN THE PRODUCTION CODE // because it leads to unnecessary slowdown of your app. mincgoptguardsmoothness(state); mincgoptguardgradient(state, 0.001); // first run alglib::mincgoptimize(state, function1_grad); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // second run - algorithm is restarted with mincgrestartfrom() x = "[10,10]"; if( _spoil_scenario==18 ) spoil_vector_by_nan(x); if( _spoil_scenario==19 ) spoil_vector_by_posinf(x); if( _spoil_scenario==20 ) spoil_vector_by_neginf(x); mincgrestartfrom(state, x); alglib::mincgoptimize(state, function1_grad); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // check OptGuard integrity report. Why do we need it at all? // Well, try breaking the gradient by adding 1.0 to some // of its components - OptGuard should report it as error. // And it may also catch unintended errors too :) optguardreport ogrep; mincgoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mincg_d_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST mincg_numdiff // Nonlinear optimization by CG with numerical differentiation // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<18; _spoil_scenario++) { try { // // This example demonstrates minimization of // // f(x,y) = 100*(x+3)^4+(y-3)^4 // // using numerical differentiation to calculate gradient. // // We also show how to use OptGuard integrity checker to catch common // problem statement errors like accidentally specifying nonsmooth target // function. // // First, we set up optimizer... // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsg = 0; if( _spoil_scenario==6 ) epsg = fp_nan; if( _spoil_scenario==7 ) epsg = fp_posinf; if( _spoil_scenario==8 ) epsg = fp_neginf; double epsf = 0; if( _spoil_scenario==9 ) epsf = fp_nan; if( _spoil_scenario==10 ) epsf = fp_posinf; if( _spoil_scenario==11 ) epsf = fp_neginf; double epsx = 0.0000000001; if( _spoil_scenario==12 ) epsx = fp_nan; if( _spoil_scenario==13 ) epsx = fp_posinf; if( _spoil_scenario==14 ) epsx = fp_neginf; double diffstep = 1.0e-6; if( _spoil_scenario==15 ) diffstep = fp_nan; if( _spoil_scenario==16 ) diffstep = fp_posinf; if( _spoil_scenario==17 ) diffstep = fp_neginf; ae_int_t maxits = 0; mincgstate state; mincgcreatef(x, diffstep, state); mincgsetcond(state, epsg, epsf, epsx, maxits); mincgsetscale(state, s); // // Then, we activate OptGuard integrity checking. // // Numerical differentiation always produces "correct" gradient // (with some truncation error, but unbiased). Thus, we just have // to check smoothness properties of the target: C0 and C1 continuity. // // Sometimes user accidentally tried to solve nonsmooth problems // with smooth optimizer. OptGuard helps to detect such situations // early, at the prototyping stage. // mincgoptguardsmoothness(state); // // Now we are ready to run the optimization // mincgreport rep; alglib::mincgoptimize(state, function1_func); mincgresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,3]", 0.005); // // ...and to check OptGuard integrity report. // // Want to challenge OptGuard? Try to make your problem // nonsmooth by replacing 100*(x+3)^4 by 100*|x+3| and // re-run optimizer. // optguardreport ogrep; mincgoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.nonc0suspected, false); _TestResult = _TestResult && doc_test_bool(ogrep.nonc1suspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "mincg_numdiff"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_v // Nonlinear least squares optimization using function vector only // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // using "V" mode of the Levenberg-Marquardt optimizer. // // Optimization algorithm uses: // * function vector f[] = {f1,f2} // // No other information (Jacobian, gradient, etc.) is needed. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.0000000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; // // Create optimizer, tell it to: // * use numerical differentiation with step equal to 0.0001 // * use unit scale for all variables (s is a unit vector) // * stop after short enough step (less than epsx) // minlmcreatev(2, x, 0.0001, state); minlmsetcond(state, epsx, maxits); minlmsetscale(state, s); // // Optimize // alglib::minlmoptimize(state, function1_fvec); // // Test optimization results // // NOTE: because we use numerical differentiation, we do not // verify Jacobian correctness - it is always "correct". // However, if you switch to analytic gradient, consider // checking it with OptGuard (see other examples). // minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_v"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_vj // Nonlinear least squares optimization using function vector and Jacobian // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // using "VJ" mode of the Levenberg-Marquardt optimizer. // // Optimization algorithm uses: // * function vector f[] = {f1,f2} // * Jacobian matrix J = {dfi/dxj}. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); double epsx = 0.0000000001; if( _spoil_scenario==6 ) epsx = fp_nan; if( _spoil_scenario==7 ) epsx = fp_posinf; if( _spoil_scenario==8 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; // // Create optimizer, tell it to: // * use analytic gradient provided by user // * use unit scale for all variables (s is a unit vector) // * stop after short enough step (less than epsx) // minlmcreatevj(2, x, state); minlmsetcond(state, epsx, maxits); minlmsetscale(state, s); // // Activate OptGuard integrity checking. // // OptGuard monitor helps to detect erroneous analytic Jacobian, // i.e. one inconsistent with actual change in the target function. // // OptGuard is essential for early prototyping stages because such // problems often result in premature termination of the optimizer // which is really hard to distinguish from the correct termination. // // IMPORTANT: JACOBIAN VERIFICATION IS PERFORMED BY MEANS OF NUMERICAL // DIFFERENTIATION, THUS DO NOT USE IT IN PRODUCTION CODE! // minlmoptguardgradient(state, 0.001); // // Optimize // alglib::minlmoptimize(state, function1_fvec, function1_jac); // // Test optimization results // minlmreport rep; minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); // // Check that OptGuard did not report errors // // NOTE: want to test OptGuard? Try breaking the Jacobian - say, add // 1.0 to some of its components. // // NOTE: unfortunately, specifics of LM optimization do not allow us // to detect errors like nonsmoothness (like we do with other // optimizers). So, only Jacobian correctness is verified. // optguardreport ogrep; minlmoptguardresults(state, ogrep); _TestResult = _TestResult && doc_test_bool(ogrep.badgradsuspected, false); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_vj"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_fgh // Nonlinear Hessian-based optimization for general functions // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = 100*(x0+3)^4+(x1-3)^4 // using "FGH" mode of the Levenberg-Marquardt optimizer. // // F is treated like a monolitic function without internal structure, // i.e. we do NOT represent it as a sum of squares. // // Optimization algorithm uses: // * function value F(x0,x1) // * gradient G={dF/dxi} // * Hessian H={d2F/(dxi*dxj)} // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsx = 0.0000000001; if( _spoil_scenario==3 ) epsx = fp_nan; if( _spoil_scenario==4 ) epsx = fp_posinf; if( _spoil_scenario==5 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; minlmcreatefgh(x, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_func, function1_grad, function1_hess); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_fgh"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_vb // Bound constrained nonlinear least squares optimization // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<13; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // with boundary constraints // // -1 <= x0 <= +1 // -1 <= x1 <= +1 // // using "V" mode of the Levenberg-Marquardt optimizer. // // Optimization algorithm uses: // * function vector f[] = {f1,f2} // // No other information (Jacobian, gradient, etc.) is needed. // real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); real_1d_array s = "[1,1]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(s); if( _spoil_scenario==4 ) spoil_vector_by_posinf(s); if( _spoil_scenario==5 ) spoil_vector_by_neginf(s); real_1d_array bndl = "[-1,-1]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(bndl); if( _spoil_scenario==7 ) spoil_vector_by_deleting_element(bndl); real_1d_array bndu = "[+1,+1]"; if( _spoil_scenario==8 ) spoil_vector_by_nan(bndu); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(bndu); double epsx = 0.0000000001; if( _spoil_scenario==10 ) epsx = fp_nan; if( _spoil_scenario==11 ) epsx = fp_posinf; if( _spoil_scenario==12 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; // // Create optimizer, tell it to: // * use numerical differentiation with step equal to 1.0 // * use unit scale for all variables (s is a unit vector) // * stop after short enough step (less than epsx) // * set box constraints // minlmcreatev(2, x, 0.0001, state); minlmsetbc(state, bndl, bndu); minlmsetcond(state, epsx, maxits); minlmsetscale(state, s); // // Optimize // alglib::minlmoptimize(state, function1_fvec); // // Test optimization results // // NOTE: because we use numerical differentiation, we do not // verify Jacobian correctness - it is always "correct". // However, if you switch to analytic gradient, consider // checking it with OptGuard (see other examples). // minlmreport rep; minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-1,+1]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_vb"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_d_restarts // Efficient restarts of LM optimizer // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // This example demonstrates minimization of F(x0,x1) = f0^2+f1^2, where // // f0(x0,x1) = 10*(x0+3)^2 // f1(x0,x1) = (x1-3)^2 // // using several starting points and efficient restarts. // real_1d_array x; double epsx = 0.0000000001; if( _spoil_scenario==0 ) epsx = fp_nan; if( _spoil_scenario==1 ) epsx = fp_posinf; if( _spoil_scenario==2 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; // // create optimizer using minlmcreatev() // x = "[10,10]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(x); if( _spoil_scenario==4 ) spoil_vector_by_posinf(x); if( _spoil_scenario==5 ) spoil_vector_by_neginf(x); minlmcreatev(2, x, 0.0001, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_fvec); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); // // restart optimizer using minlmrestartfrom() // // we can use different starting point, different function, // different stopping conditions, but problem size // must remain unchanged. // x = "[4,4]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(x); if( _spoil_scenario==7 ) spoil_vector_by_posinf(x); if( _spoil_scenario==8 ) spoil_vector_by_neginf(x); minlmrestartfrom(state, x); alglib::minlmoptimize(state, function2_fvec); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[0,1]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_d_restarts"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_t_1 // Nonlinear least squares optimization, FJ scheme (obsolete, but supported) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsx = 0.0000000001; if( _spoil_scenario==3 ) epsx = fp_nan; if( _spoil_scenario==4 ) epsx = fp_posinf; if( _spoil_scenario==5 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; minlmcreatefj(2, x, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_func, function1_jac); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_t_1"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST minlm_t_2 // Nonlinear least squares optimization, FGJ scheme (obsolete, but supported) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array x = "[0,0]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double epsx = 0.0000000001; if( _spoil_scenario==3 ) epsx = fp_nan; if( _spoil_scenario==4 ) epsx = fp_posinf; if( _spoil_scenario==5 ) epsx = fp_neginf; ae_int_t maxits = 0; minlmstate state; minlmreport rep; minlmcreatefgj(2, x, state); minlmsetcond(state, epsx, maxits); alglib::minlmoptimize(state, function1_func, function1_grad, function1_jac); minlmresults(state, x, rep); _TestResult = _TestResult && doc_test_real_vector(x, "[-3,+3]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "minlm_t_2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_base // Basic functionality (moments, adev, median, percentile) // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { real_1d_array x = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); double mean; double variance; double skewness; double kurtosis; double adev; double p; double v; // // Here we demonstrate calculation of sample moments // (mean, variance, skewness, kurtosis) // samplemoments(x, mean, variance, skewness, kurtosis); _TestResult = _TestResult && doc_test_real(mean, 28.5, 0.01); _TestResult = _TestResult && doc_test_real(variance, 801.1667, 0.01); _TestResult = _TestResult && doc_test_real(skewness, 0.5751, 0.01); _TestResult = _TestResult && doc_test_real(kurtosis, -1.2666, 0.01); // // Average deviation // sampleadev(x, adev); _TestResult = _TestResult && doc_test_real(adev, 23.2, 0.01); // // Median and percentile // samplemedian(x, v); _TestResult = _TestResult && doc_test_real(v, 20.5, 0.01); p = 0.5; if( _spoil_scenario==3 ) p = fp_nan; if( _spoil_scenario==4 ) p = fp_posinf; if( _spoil_scenario==5 ) p = fp_neginf; samplepercentile(x, p, v); _TestResult = _TestResult && doc_test_real(v, 20.5, 0.01); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_base"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_c2 // Correlation (covariance) between two random variables // printf("50/151\n"); _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<10; _spoil_scenario++) { try { // // We have two samples - x and y, and want to measure dependency between them // real_1d_array x = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x); real_1d_array y = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y); double v; // // Three dependency measures are calculated: // * covariation // * Pearson correlation // * Spearman rank correlation // v = cov2(x, y); _TestResult = _TestResult && doc_test_real(v, 82.5, 0.001); v = pearsoncorr2(x, y); _TestResult = _TestResult && doc_test_real(v, 0.9627, 0.001); v = spearmancorr2(x, y); _TestResult = _TestResult && doc_test_real(v, 1.000, 0.001); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_c2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_cm // Correlation (covariance) between components of random vector // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // X is a sample matrix: // * I-th row corresponds to I-th observation // * J-th column corresponds to J-th variable // real_2d_array x = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); real_2d_array c; // // Three dependency measures are calculated: // * covariation // * Pearson correlation // * Spearman rank correlation // // Result is stored into C, with C[i,j] equal to correlation // (covariance) between I-th and J-th variables of X. // covm(x, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[1.80,0.60,-1.40],[0.60,0.70,-0.80],[-1.40,-0.80,14.70]]", 0.01); pearsoncorrm(x, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[1.000,0.535,-0.272],[0.535,1.000,-0.249],[-0.272,-0.249,1.000]]", 0.01); spearmancorrm(x, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[1.000,0.556,-0.306],[0.556,1.000,-0.750],[-0.306,-0.750,1.000]]", 0.01); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_cm"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_d_cm2 // Correlation (covariance) between two random vectors // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<6; _spoil_scenario++) { try { // // X and Y are sample matrices: // * I-th row corresponds to I-th observation // * J-th column corresponds to J-th variable // real_2d_array x = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==0 ) spoil_matrix_by_nan(x); if( _spoil_scenario==1 ) spoil_matrix_by_posinf(x); if( _spoil_scenario==2 ) spoil_matrix_by_neginf(x); real_2d_array y = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==3 ) spoil_matrix_by_nan(y); if( _spoil_scenario==4 ) spoil_matrix_by_posinf(y); if( _spoil_scenario==5 ) spoil_matrix_by_neginf(y); real_2d_array c; // // Three dependency measures are calculated: // * covariation // * Pearson correlation // * Spearman rank correlation // // Result is stored into C, with C[i,j] equal to correlation // (covariance) between I-th variable of X and J-th variable of Y. // covm2(x, y, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[4.100,-3.250],[2.450,-1.500],[13.450,-5.750]]", 0.01); pearsoncorrm2(x, y, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.519,-0.699],[0.497,-0.518],[0.596,-0.433]]", 0.01); spearmancorrm2(x, y, c); _TestResult = _TestResult && doc_test_real_matrix(c, "[[0.541,-0.649],[0.216,-0.433],[0.433,-0.135]]", 0.01); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_d_cm2"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_t_base // Tests ability to detect errors in inputs // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<34; _spoil_scenario++) { try { double mean; double variance; double skewness; double kurtosis; double adev; double p; double v; // // first, we test short form of functions // real_1d_array x1 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x1); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x1); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x1); samplemoments(x1, mean, variance, skewness, kurtosis); real_1d_array x2 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==3 ) spoil_vector_by_nan(x2); if( _spoil_scenario==4 ) spoil_vector_by_posinf(x2); if( _spoil_scenario==5 ) spoil_vector_by_neginf(x2); sampleadev(x2, adev); real_1d_array x3 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==6 ) spoil_vector_by_nan(x3); if( _spoil_scenario==7 ) spoil_vector_by_posinf(x3); if( _spoil_scenario==8 ) spoil_vector_by_neginf(x3); samplemedian(x3, v); real_1d_array x4 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==9 ) spoil_vector_by_nan(x4); if( _spoil_scenario==10 ) spoil_vector_by_posinf(x4); if( _spoil_scenario==11 ) spoil_vector_by_neginf(x4); p = 0.5; if( _spoil_scenario==12 ) p = fp_nan; if( _spoil_scenario==13 ) p = fp_posinf; if( _spoil_scenario==14 ) p = fp_neginf; samplepercentile(x4, p, v); // // and then we test full form // real_1d_array x5 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(x5); if( _spoil_scenario==16 ) spoil_vector_by_posinf(x5); if( _spoil_scenario==17 ) spoil_vector_by_neginf(x5); if( _spoil_scenario==18 ) spoil_vector_by_deleting_element(x5); samplemoments(x5, 10, mean, variance, skewness, kurtosis); real_1d_array x6 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==19 ) spoil_vector_by_nan(x6); if( _spoil_scenario==20 ) spoil_vector_by_posinf(x6); if( _spoil_scenario==21 ) spoil_vector_by_neginf(x6); if( _spoil_scenario==22 ) spoil_vector_by_deleting_element(x6); sampleadev(x6, 10, adev); real_1d_array x7 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==23 ) spoil_vector_by_nan(x7); if( _spoil_scenario==24 ) spoil_vector_by_posinf(x7); if( _spoil_scenario==25 ) spoil_vector_by_neginf(x7); if( _spoil_scenario==26 ) spoil_vector_by_deleting_element(x7); samplemedian(x7, 10, v); real_1d_array x8 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==27 ) spoil_vector_by_nan(x8); if( _spoil_scenario==28 ) spoil_vector_by_posinf(x8); if( _spoil_scenario==29 ) spoil_vector_by_neginf(x8); if( _spoil_scenario==30 ) spoil_vector_by_deleting_element(x8); p = 0.5; if( _spoil_scenario==31 ) p = fp_nan; if( _spoil_scenario==32 ) p = fp_posinf; if( _spoil_scenario==33 ) p = fp_neginf; samplepercentile(x8, 10, p, v); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_t_base"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST basestat_t_covcorr // Tests ability to detect errors in inputs // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<126; _spoil_scenario++) { try { double v; real_2d_array c; // // 2-sample short-form cov/corr are tested // real_1d_array x1 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x1); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x1); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x1); if( _spoil_scenario==3 ) spoil_vector_by_adding_element(x1); if( _spoil_scenario==4 ) spoil_vector_by_deleting_element(x1); real_1d_array y1 = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==5 ) spoil_vector_by_nan(y1); if( _spoil_scenario==6 ) spoil_vector_by_posinf(y1); if( _spoil_scenario==7 ) spoil_vector_by_neginf(y1); if( _spoil_scenario==8 ) spoil_vector_by_adding_element(y1); if( _spoil_scenario==9 ) spoil_vector_by_deleting_element(y1); v = cov2(x1, y1); real_1d_array x2 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==10 ) spoil_vector_by_nan(x2); if( _spoil_scenario==11 ) spoil_vector_by_posinf(x2); if( _spoil_scenario==12 ) spoil_vector_by_neginf(x2); if( _spoil_scenario==13 ) spoil_vector_by_adding_element(x2); if( _spoil_scenario==14 ) spoil_vector_by_deleting_element(x2); real_1d_array y2 = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==15 ) spoil_vector_by_nan(y2); if( _spoil_scenario==16 ) spoil_vector_by_posinf(y2); if( _spoil_scenario==17 ) spoil_vector_by_neginf(y2); if( _spoil_scenario==18 ) spoil_vector_by_adding_element(y2); if( _spoil_scenario==19 ) spoil_vector_by_deleting_element(y2); v = pearsoncorr2(x2, y2); real_1d_array x3 = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==20 ) spoil_vector_by_nan(x3); if( _spoil_scenario==21 ) spoil_vector_by_posinf(x3); if( _spoil_scenario==22 ) spoil_vector_by_neginf(x3); if( _spoil_scenario==23 ) spoil_vector_by_adding_element(x3); if( _spoil_scenario==24 ) spoil_vector_by_deleting_element(x3); real_1d_array y3 = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==25 ) spoil_vector_by_nan(y3); if( _spoil_scenario==26 ) spoil_vector_by_posinf(y3); if( _spoil_scenario==27 ) spoil_vector_by_neginf(y3); if( _spoil_scenario==28 ) spoil_vector_by_adding_element(y3); if( _spoil_scenario==29 ) spoil_vector_by_deleting_element(y3); v = spearmancorr2(x3, y3); // // 2-sample full-form cov/corr are tested // real_1d_array x1a = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==30 ) spoil_vector_by_nan(x1a); if( _spoil_scenario==31 ) spoil_vector_by_posinf(x1a); if( _spoil_scenario==32 ) spoil_vector_by_neginf(x1a); if( _spoil_scenario==33 ) spoil_vector_by_deleting_element(x1a); real_1d_array y1a = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==34 ) spoil_vector_by_nan(y1a); if( _spoil_scenario==35 ) spoil_vector_by_posinf(y1a); if( _spoil_scenario==36 ) spoil_vector_by_neginf(y1a); if( _spoil_scenario==37 ) spoil_vector_by_deleting_element(y1a); v = cov2(x1a, y1a, 10); real_1d_array x2a = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==38 ) spoil_vector_by_nan(x2a); if( _spoil_scenario==39 ) spoil_vector_by_posinf(x2a); if( _spoil_scenario==40 ) spoil_vector_by_neginf(x2a); if( _spoil_scenario==41 ) spoil_vector_by_deleting_element(x2a); real_1d_array y2a = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==42 ) spoil_vector_by_nan(y2a); if( _spoil_scenario==43 ) spoil_vector_by_posinf(y2a); if( _spoil_scenario==44 ) spoil_vector_by_neginf(y2a); if( _spoil_scenario==45 ) spoil_vector_by_deleting_element(y2a); v = pearsoncorr2(x2a, y2a, 10); real_1d_array x3a = "[0,1,4,9,16,25,36,49,64,81]"; if( _spoil_scenario==46 ) spoil_vector_by_nan(x3a); if( _spoil_scenario==47 ) spoil_vector_by_posinf(x3a); if( _spoil_scenario==48 ) spoil_vector_by_neginf(x3a); if( _spoil_scenario==49 ) spoil_vector_by_deleting_element(x3a); real_1d_array y3a = "[0,1,2,3,4,5,6,7,8,9]"; if( _spoil_scenario==50 ) spoil_vector_by_nan(y3a); if( _spoil_scenario==51 ) spoil_vector_by_posinf(y3a); if( _spoil_scenario==52 ) spoil_vector_by_neginf(y3a); if( _spoil_scenario==53 ) spoil_vector_by_deleting_element(y3a); v = spearmancorr2(x3a, y3a, 10); // // vector short-form cov/corr are tested. // real_2d_array x4 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==54 ) spoil_matrix_by_nan(x4); if( _spoil_scenario==55 ) spoil_matrix_by_posinf(x4); if( _spoil_scenario==56 ) spoil_matrix_by_neginf(x4); covm(x4, c); real_2d_array x5 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==57 ) spoil_matrix_by_nan(x5); if( _spoil_scenario==58 ) spoil_matrix_by_posinf(x5); if( _spoil_scenario==59 ) spoil_matrix_by_neginf(x5); pearsoncorrm(x5, c); real_2d_array x6 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==60 ) spoil_matrix_by_nan(x6); if( _spoil_scenario==61 ) spoil_matrix_by_posinf(x6); if( _spoil_scenario==62 ) spoil_matrix_by_neginf(x6); spearmancorrm(x6, c); // // vector full-form cov/corr are tested. // real_2d_array x7 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==63 ) spoil_matrix_by_nan(x7); if( _spoil_scenario==64 ) spoil_matrix_by_posinf(x7); if( _spoil_scenario==65 ) spoil_matrix_by_neginf(x7); if( _spoil_scenario==66 ) spoil_matrix_by_deleting_row(x7); if( _spoil_scenario==67 ) spoil_matrix_by_deleting_col(x7); covm(x7, 5, 3, c); real_2d_array x8 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==68 ) spoil_matrix_by_nan(x8); if( _spoil_scenario==69 ) spoil_matrix_by_posinf(x8); if( _spoil_scenario==70 ) spoil_matrix_by_neginf(x8); if( _spoil_scenario==71 ) spoil_matrix_by_deleting_row(x8); if( _spoil_scenario==72 ) spoil_matrix_by_deleting_col(x8); pearsoncorrm(x8, 5, 3, c); real_2d_array x9 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==73 ) spoil_matrix_by_nan(x9); if( _spoil_scenario==74 ) spoil_matrix_by_posinf(x9); if( _spoil_scenario==75 ) spoil_matrix_by_neginf(x9); if( _spoil_scenario==76 ) spoil_matrix_by_deleting_row(x9); if( _spoil_scenario==77 ) spoil_matrix_by_deleting_col(x9); spearmancorrm(x9, 5, 3, c); // // cross-vector short-form cov/corr are tested. // real_2d_array x10 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==78 ) spoil_matrix_by_nan(x10); if( _spoil_scenario==79 ) spoil_matrix_by_posinf(x10); if( _spoil_scenario==80 ) spoil_matrix_by_neginf(x10); real_2d_array y10 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==81 ) spoil_matrix_by_nan(y10); if( _spoil_scenario==82 ) spoil_matrix_by_posinf(y10); if( _spoil_scenario==83 ) spoil_matrix_by_neginf(y10); covm2(x10, y10, c); real_2d_array x11 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==84 ) spoil_matrix_by_nan(x11); if( _spoil_scenario==85 ) spoil_matrix_by_posinf(x11); if( _spoil_scenario==86 ) spoil_matrix_by_neginf(x11); real_2d_array y11 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==87 ) spoil_matrix_by_nan(y11); if( _spoil_scenario==88 ) spoil_matrix_by_posinf(y11); if( _spoil_scenario==89 ) spoil_matrix_by_neginf(y11); pearsoncorrm2(x11, y11, c); real_2d_array x12 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==90 ) spoil_matrix_by_nan(x12); if( _spoil_scenario==91 ) spoil_matrix_by_posinf(x12); if( _spoil_scenario==92 ) spoil_matrix_by_neginf(x12); real_2d_array y12 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==93 ) spoil_matrix_by_nan(y12); if( _spoil_scenario==94 ) spoil_matrix_by_posinf(y12); if( _spoil_scenario==95 ) spoil_matrix_by_neginf(y12); spearmancorrm2(x12, y12, c); // // cross-vector full-form cov/corr are tested. // real_2d_array x13 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==96 ) spoil_matrix_by_nan(x13); if( _spoil_scenario==97 ) spoil_matrix_by_posinf(x13); if( _spoil_scenario==98 ) spoil_matrix_by_neginf(x13); if( _spoil_scenario==99 ) spoil_matrix_by_deleting_row(x13); if( _spoil_scenario==100 ) spoil_matrix_by_deleting_col(x13); real_2d_array y13 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==101 ) spoil_matrix_by_nan(y13); if( _spoil_scenario==102 ) spoil_matrix_by_posinf(y13); if( _spoil_scenario==103 ) spoil_matrix_by_neginf(y13); if( _spoil_scenario==104 ) spoil_matrix_by_deleting_row(y13); if( _spoil_scenario==105 ) spoil_matrix_by_deleting_col(y13); covm2(x13, y13, 5, 3, 2, c); real_2d_array x14 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==106 ) spoil_matrix_by_nan(x14); if( _spoil_scenario==107 ) spoil_matrix_by_posinf(x14); if( _spoil_scenario==108 ) spoil_matrix_by_neginf(x14); if( _spoil_scenario==109 ) spoil_matrix_by_deleting_row(x14); if( _spoil_scenario==110 ) spoil_matrix_by_deleting_col(x14); real_2d_array y14 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==111 ) spoil_matrix_by_nan(y14); if( _spoil_scenario==112 ) spoil_matrix_by_posinf(y14); if( _spoil_scenario==113 ) spoil_matrix_by_neginf(y14); if( _spoil_scenario==114 ) spoil_matrix_by_deleting_row(y14); if( _spoil_scenario==115 ) spoil_matrix_by_deleting_col(y14); pearsoncorrm2(x14, y14, 5, 3, 2, c); real_2d_array x15 = "[[1,0,1],[1,1,0],[-1,1,0],[-2,-1,1],[-1,0,9]]"; if( _spoil_scenario==116 ) spoil_matrix_by_nan(x15); if( _spoil_scenario==117 ) spoil_matrix_by_posinf(x15); if( _spoil_scenario==118 ) spoil_matrix_by_neginf(x15); if( _spoil_scenario==119 ) spoil_matrix_by_deleting_row(x15); if( _spoil_scenario==120 ) spoil_matrix_by_deleting_col(x15); real_2d_array y15 = "[[2,3],[2,1],[-1,6],[-9,9],[7,1]]"; if( _spoil_scenario==121 ) spoil_matrix_by_nan(y15); if( _spoil_scenario==122 ) spoil_matrix_by_posinf(y15); if( _spoil_scenario==123 ) spoil_matrix_by_neginf(y15); if( _spoil_scenario==124 ) spoil_matrix_by_deleting_row(y15); if( _spoil_scenario==125 ) spoil_matrix_by_deleting_col(y15); spearmancorrm2(x15, y15, 5, 3, 2, c); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "basestat_t_covcorr"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ssa_d_basic // Simple SSA analysis demo // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate SSA trend/noise separation for some toy problem: // small monotonically growing series X are analyzed with 3-tick window // and "top-K" version of SSA, which selects K largest singular vectors // for analysis, with K=1. // ssamodel s; real_1d_array x = "[0,0.5,1,1,1.5,2]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // First, we create SSA model, set its properties and add dataset. // // We use window with width=3 and configure model to use direct SSA // algorithm - one which runs exact O(N*W^2) analysis - to extract // one top singular vector. Well, it is toy problem :) // // NOTE: SSA model may store and analyze more than one sequence // (say, different sequences may correspond to data collected // from different devices) // ssacreate(s); ssasetwindow(s, 3); ssaaddsequence(s, x); ssasetalgotopkdirect(s, 1); // // Now we begin analysis. Internally SSA model stores everything it needs: // data, settings, solvers and so on. Right after first call to analysis- // related function it will analyze dataset, build basis and perform analysis. // // Subsequent calls to analysis functions will reuse previously computed // basis, unless you invalidate it by changing model settings (or dataset). // real_1d_array trend; real_1d_array noise; ssaanalyzesequence(s, x, trend, noise); _TestResult = _TestResult && doc_test_real_vector(trend, "[0.3815,0.5582,0.7810,1.0794,1.5041,2.0105]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "ssa_d_basic"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ssa_d_forecast // Simple SSA forecasting demo // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<3; _spoil_scenario++) { try { // // Here we demonstrate SSA forecasting on some toy problem with clearly // visible linear trend and small amount of noise. // ssamodel s; real_1d_array x = "[0.05,0.96,2.04,3.11,3.97,5.03,5.98,7.02,8.02]"; if( _spoil_scenario==0 ) spoil_vector_by_nan(x); if( _spoil_scenario==1 ) spoil_vector_by_posinf(x); if( _spoil_scenario==2 ) spoil_vector_by_neginf(x); // // First, we create SSA model, set its properties and add dataset. // // We use window with width=3 and configure model to use direct SSA // algorithm - one which runs exact O(N*W^2) analysis - to extract // two top singular vectors. Well, it is toy problem :) // // NOTE: SSA model may store and analyze more than one sequence // (say, different sequences may correspond to data collected // from different devices) // ssacreate(s); ssasetwindow(s, 3); ssaaddsequence(s, x); ssasetalgotopkdirect(s, 2); // // Now we begin analysis. Internally SSA model stores everything it needs: // data, settings, solvers and so on. Right after first call to analysis- // related function it will analyze dataset, build basis and perform analysis. // // Subsequent calls to analysis functions will reuse previously computed // basis, unless you invalidate it by changing model settings (or dataset). // // In this example we show how to use ssaforecastlast() function, which // predicts changed in the last sequence of the dataset. If you want to // perform prediction for some other sequence, use ssaforecastsequence(). // real_1d_array trend; ssaforecastlast(s, 3, trend); // // Well, we expected it to be [9,10,11]. There exists some difference, // which can be explained by the artificial noise in the dataset. // _TestResult = _TestResult && doc_test_real_vector(trend, "[9.0005,9.9322,10.8051]", 0.005); _TestResult = _TestResult && (_spoil_scenario==-1); } catch(ap_error) { _TestResult = _TestResult && (_spoil_scenario!=-1); } } if( !_TestResult) { printf("%-32s FAILED\n", "ssa_d_forecast"); fflush(stdout); } _TotalResult = _TotalResult && _TestResult; // // TEST ssa_d_realtime // Real-time SSA algorithm with fast incremental updates // _TestResult = true; for(_spoil_scenario=-1; _spoil_scenario<9; _spoil_scenario++) { try { // // Suppose that you have a constant stream of incoming data, and you want // to regularly perform singular spectral analysis of this stream. // // One full run of direct algorithm costs O(N*Width^2) operations, so // the more points you have, the more it costs to rebuild basis from // scratch. // // Luckily we have incremental SSA algorithm which can perform quick // updates of already computed basis in O(K*Width^2) ops, where K // is a number of singular vectors extracted. Usually it is orders of // magnitude faster than full update of the basis. // // In this example we start from some initial dataset x0. Then we // start appending elements one by one to the end of the last sequence. // // NOTE: direct algorithm also supports incremental updates, but // with O(Width^3) cost. Typically K<