splines/0000755000175000017500000000000012627052101010671 5ustar nirnirsplines/INDEX0000644000175000017500000000023712627052101011465 0ustar nirniranalysis >> Data analysis Spline functions bin_values catmullrom csapi csape csaps csaps_sel dedup fnder fnplt fnval tpaps tps_val tps_val_der splines/COPYING0000644000175000017500000010451312627052101011730 0ustar nirnir 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 . splines/CITATION0000644000175000017500000000031612627052101012026 0ustar nirnir@software{splines, author = {Krakauer, Nir Y. and others}, title = {Splines Package for GNU Octave}, url = {http://octave.sourceforge.net/splines}, version = {1.2.9}, date = {2015-11-28}, } splines/DESCRIPTION0000644000175000017500000000045012627052101012376 0ustar nirnirName: splines Version: 1.2.9 Date: 2015-11-28 Author: various authors Maintainer: Nir Krakauer Title: Splines. Description: Additional spline functions. Categories: Splines Depends: octave (>= 3.6.0) Autoload: no License: GPLv3+, public domain Url: http://octave.sf.net splines/NEWS0000644000175000017500000000571712627052101011402 0ustar nirnirSummary of important user-visible changes for splines 1.2.9: ------------------------------------------------------------------- ** new function tps_val_der ** vectorization option for speedup of tps_val Summary of important user-visible changes for splines 1.2.8: ------------------------------------------------------------------- ** csaps now returns spline uncertainty at the fitting points xi, not at the data points x Summary of important user-visible changes for splines 1.2.7: ------------------------------------------------------------------- ** New regularization option (df_bound) in csaps_sel ** Bug fix in csape Summary of important user-visible changes for splines 1.2.6: ------------------------------------------------------------------- ** New preprocessing function bin_values Summary of important user-visible changes for splines 1.2.5: ------------------------------------------------------------------- ** Efficiency improvement in csaps_sel Summary of important user-visible changes for splines 1.2.4: ------------------------------------------------------------------- ** Bug fix in csape Summary of important user-visible changes for splines 1.2.3: ------------------------------------------------------------------- ** New regularization option (vm) in csaps_sel ** Checking for NaNs added in csaps and csaps_sel; dedup now can remove NaNs ** Bug fix in csape Summary of important user-visible changes for splines 1.2.2: ------------------------------------------------------------------- ** Bug fix in csaps and csaps_sel Summary of important user-visible changes for splines 1.2.1: ------------------------------------------------------------------- ** Points passed to csaps and csaps_sel now expected to be in strictly ascending order; new function dedup added to sort points and average values given at the same point Summary of important user-visible changes for splines 1.2.0: ------------------------------------------------------------------- ** The following functions are new: tpaps tps_val Summary of important user-visible changes for splines 1.1.2: ------------------------------------------------------------------- ** automatic smoothing parameter selection in csaps fixed ** calculation of spline coefficients for unequally spaced points in csaps fixed Summary of important user-visible changes for splines 1.1.1: ------------------------------------------------------------------- ** csape fixed to work correctly for matrix inputs ** csaps and csaps_sel fixed to extrapolate linearly Summary of important user-visible changes for splines 1.1.0: ------------------------------------------------------------------- ** The following functions are new: csaps csaps_sel ** fnder() and csape() have been fixed for compatibility with the latest Octave versions. ** splines package is now dependent on GNU Octave version 3.6.0 or later. ** Package is no longer automatically loaded. splines/inst/0000755000175000017500000000000012627052101011646 5ustar nirnirsplines/inst/fnder.m0000644000175000017500000000240112627052101013117 0ustar nirnir## Copyright (C) 2001 Kai Habel ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} { } fnder (@var{pp}, @var{order}) ## differentiate the spline in pp-form ## ## @seealso{ppval} ## @end deftypefn ## Author: Kai Habel ## Date: 20. feb 2001 function dpp = fnder (pp, o) if (nargin < 1 || nargin > 2) print_usage; endif if (nargin < 2) o = 1; endif [X, P, N, K, D] = unmkpp (pp); c = columns (P); r = rows (P); for i = 1:o #pp.P = polyder (pp.P); matrix capable polyder is needed. P = P(:, 1:c - 1) .* kron ((c - 1):- 1:1, ones (r,1)); endfor dpp = mkpp (X, P); endfunction splines/inst/csaps_sel.m0000644000175000017500000002711112627052101014002 0ustar nirnir## Copyright (C) 2012 Nir Krakauer ## ## 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 . ## -*- texinfo -*- ## @deftypefn{Function File}{[@var{yi} @var{p} @var{sigma2},@var{unc_y}] =} csaps_sel(@var{x}, @var{y}, @var{xi}, @var{w}=[], @var{crit}=[]) ## @deftypefnx{Function File}{[@var{pp} @var{p} @var{sigma2},@var{unc_y}] =} csaps_sel(@var{x}, @var{y}, [], @var{w}=[], @var{crit}=[]) ## ## Cubic spline approximation with smoothing parameter estimation @* ## Approximately interpolates [@var{x},@var{y}], weighted by @var{w} (inverse variance; if not given, equal weighting is assumed), at @var{xi}. ## ## The chosen cubic spline with natural boundary conditions @var{pp}(@var{x}) minimizes @var{p} Sum_i @var{w}_i*(@var{y}_i - @var{pp}(@var{x}_i))^2 + (1-@var{p}) Int @var{pp}''(@var{x}) d@var{x}. ## ## A selection criterion @var{crit} is used to find a suitable value for @var{p} (between 0 and 1); possible values for @var{crit} are `vm' (Vapnik's measure [Cherkassky and Mulier 2007] from statistical learning theory); `aicc' (corrected Akaike information criterion, the default); `aic' (original Akaike information criterion); `gcv' (generalized cross validation). ## ## If @var{crit} is a nonnegative scalar instead of a string, then @var{p} is chosen to so that the mean square scaled residual Mean_i (@var{w}_i*(@var{y}_i - @var{pp}(@var{x}_i))^2) is approximately equal to @var{crit}. If @var{crit} is a negative scalar, then @var{p} is chosen so that the effective number of degrees of freedom in the spline fit (which ranges from 2 when @var{p} = 0 to @var{n} when @var{p} = 1) is approximately equal to -@var{crit}. ## ## @var{x} and @var{w} should be @var{n} by 1 in size; @var{y} should be @var{n} by @var{m}; @var{xi} should be @var{k} by 1; the values in @var{x} should be distinct and in ascending order; the values in @var{w} should be nonzero. ## ## Returns the smoothing spline @var{pp} or its values @var{yi} at the desired @var{xi}; the selected @var{p}; the estimated data scatter (variance from the smooth trend) @var{sigma2}; the estimated uncertainty (SD) of the smoothing spline fit at each @var{x} value, @var{unc_y}; and the estimated number of degrees of freedom @var{df} (out of @var{n}) used in the fit. ## ## For small @var{n}, the optimization uses singular value decomposition of an @var{n} by @var{n} matrix in order to quickly compute the residual size and model degrees of freedom for many @var{p} values for the optimization (Craven and Wahba 1979). For large @var{n} (currently >300), an asymptotically more computation and storage efficient method that takes advantage of the sparsity of the problem's coefficient matrices is used (Hutchinson and de Hoog 1985). ## ## References: ## ## Vladimir Cherkassky and Filip Mulier (2007), Learning from Data: Concepts, Theory, and Methods. Wiley, Chapter 4 ## ## Carl de Boor (1978), A Practical Guide to Splines, Springer, Chapter XIV ## ## Clifford M. Hurvich, Jeffrey S. Simonoff, Chih-Ling Tsai (1998), Smoothing parameter selection in nonparametric regression using an improved Akaike information criterion, J. Royal Statistical Society, 60B:271-293 ## ## M. F. Hutchinson and F. R. de Hoog (1985), Smoothing noisy data with spline functions, Numerische Mathematik, 47:99-106 ## ## M. F. Hutchinson (1986), Algorithm 642: A fast procedure for calculating minimum cross-validation cubic smoothing splines, ACM Transactions on Mathematical Software, 12:150-153 ## ## Grace Wahba (1983), Bayesian ``confidence intervals'' for the cross-validated smoothing spline, J Royal Statistical Society, 45B:133-150 ## ## @end deftypefn ## @seealso{csaps, spline, csapi, ppval, dedup, bin_values, gcvspl} ## Author: Nir Krakauer function [ret,p,sigma2,unc_y,df]=csaps_sel(x,y,xi,w,crit) if (nargin < 5) crit = []; if(nargin < 4) w = []; if(nargin < 3) xi = []; endif endif endif if(columns(x) > 1) x = x'; y = y'; w = w'; endif if any (isnan ([x y w](:)) ) error('NaN values in inputs; pre-process to remove them') endif h = diff(x); if any(h <= 0) error('x must be strictly increasing; pre-process to achieve this') endif n = numel(x); if isempty(w) w = ones(n, 1); end if isscalar(crit) if crit == 0 || crit <= -n #return an exact cubic spline interpolation [ret,p]=csaps(x,y,1,xi,w); sigma2 = 0; unc_y = zeros(size(x)); return elseif crit > 0 w = w ./ crit; #adjust the sample weights so that the target mean square scaled residual is 1 crit = 'msr_bound'; else #negative value -- target degrees of freedom of fit if crit >= -2 #return linear regression p = 0; else global df_target df_target = -crit; crit = 'df_bound'; endif endif end if isempty(crit) crit = 'aicc'; end R = spdiags([h(2:end) 2*(h(1:end-1) + h(2:end)) h(1:end-1)], [-1 0 1], n-2, n-2); QT = spdiags([1 ./ h(1:end-1) -(1 ./ h(1:end-1) + 1 ./ h(2:end)) 1 ./ h(2:end)], [0 1 2], n-2, n); chol_method = (n > 300); #use a sparse Cholesky decomposition followed by solving for only the central bands of the inverse to solve for large n (faster), and singular value decomposition for small n (less prone to numerical error if data values are spaced close together) if chol_method penalty_function = @(p) penalty_compute_chol(p, QT, R, y, w, n, crit); else ##determine influence matrix for different p without repeated inversion [U D V] = svd(diag(1 ./ sqrt(w))*QT'*sqrtm(inv(R)), 0); D = diag(D).^2; penalty_function = @(p) penalty_compute(p, U, D, y, w, n, crit); end if ~exist("p", "var") ##choose p by minimizing the penalty function p = fminbnd(penalty_function, 0, 1); endif ## estimate the trend uncertainty if isargout (3) || isargout (4) || isargout (5) if chol_method [MSR, df] = penalty_terms_chol(p, QT, R, y, w, n); else H = influence_matrix(p, U, D, n, w); [MSR, df] = penalty_terms(H, y, w); end sigma2 = mean(MSR(:)) * (n / (n-df)); #estimated data error variance (wahba83) if isargout (4) if chol_method Hd = influence_matrix_diag_chol(p, QT, R, y, w, n); else Hd = diag(H); endif unc_y = sqrt(sigma2 * Hd ./ w); #uncertainty (SD) of fitted curve at each input x-value (hutchinson86) endif endif ## construct the fitted smoothing spline if isargout (1) ret = csaps (x,y,p,xi,w); endif endfunction function H = influence_matrix(p, U, D, n, w) #returns influence matrix for given p H = speye(n) - U * diag(D ./ (D + (p / (6*(1-p))))) * U'; H = diag(1 ./ sqrt(w)) * H * diag(sqrt(w)); #rescale to original units endfunction function [MSR, Ht] = penalty_terms(H, y, w) MSR = mean(w .* (y - (H*y)) .^ 2); #mean square residual Ht = trace(H); #effective number of fitted parameters endfunction function Hd = influence_matrix_diag_chol(p, QT, R, y, w, n) #LDL factorization of 6*(1-p)*QT*diag(1 ./ w)*QT' + p*R U = chol(6*(1-p)*QT*diag(1 ./ w)*QT' + p*R, 'upper'); d = 1 ./ diag(U); U = diag(d)*U; d = d .^ 2; #5 central bands in the inverse of 6*(1-p)*QT*diag(1 ./ w)*QT' + p*R Binv = banded_matrix_inverse(d, U, 2); Hd = full(diag(speye(n) - (6*(1-p))*diag(1 ./ w)*QT'*Binv*QT)); endfunction function [MSR, Ht] = penalty_terms_chol(p, QT, R, y, w, n) #LDL factorization of 6*(1-p)*QT*diag(1 ./ w)*QT' + p*R U = chol(6*(1-p)*QT*diag(1 ./ w)*QT' + p*R, 'upper'); d = 1 ./ diag(U); U = diag(d)*U; d = d .^ 2; Binv = banded_matrix_inverse(d, U, 2); #5 central bands in the inverse of 6*(1-p)*QT*diag(1 ./ w)*QT' + p*R Ht = 2 + trace(speye(n-2) - (6*(1-p))*QT*diag(1 ./ w)*QT'*Binv); MSR = mean(w .* ((6*(1-p)*diag(1 ./ w)*QT'*((6*(1-p)*QT*diag(1 ./ w)*QT' + p*R) \ (QT*y)))) .^ 2); endfunction function J = vm(MSR, Ht, n) #Vapnik-Chervonenkis penalization factor or Vapnik's measure in cherkassky07, p. 129 p = Ht/n; if p == 0 J = mean(log(MSR)(:)) - log(1 - sqrt(log(n)/(2*n))); elseif n == 0 || (p*(1 - log(p)) + log(n)/(2*n)) >= 1 J = Inf; else J = mean(log(MSR)(:)) - log(1 - sqrt(p*(1 - log(p)) + log(n)/(2*n))); endif endfunction function J = aicc(MSR, Ht, n) J = mean(log(MSR)(:)) + 2 * (Ht + 1) / max(n - Ht - 2, 0); #hurvich98, taking the average if there are multiple data sets as in woltring86 endfunction function J = aic(MSR, Ht, n) J = mean(log(MSR)(:)) + 2 * Ht / n; endfunction function J = gcv(MSR, Ht, n) J = mean(log(MSR)(:)) - 2 * log(1 - Ht / n); endfunction function J = msr_bound(MSR, Ht, n) J = mean(MSR(:) - 1) .^ 2; endfunction function J = df_bound(MSR, Ht, n) global df_target J = (Ht - df_target) .^ 2; endfunction function J = penalty_compute(p, U, D, y, w, n, crit) #evaluates a user-supplied penalty function crit at given p H = influence_matrix(p, U, D, n, w); [MSR, Ht] = penalty_terms(H, y, w); J = feval(crit, MSR, Ht, n); if ~isfinite(J) J = Inf; endif endfunction function J = penalty_compute_chol(p, QT, R, y, w, n, crit) #evaluates a user-supplied penalty function crit at given p [MSR, Ht] = penalty_terms_chol(p, QT, R, y, w, n); J = feval(crit, MSR, Ht, n); if ~isfinite(J) J = Inf; endif endfunction function Binv = banded_matrix_inverse(d, U, m) #given a (2m+1)-banded, symmetric n x n matrix B = U'*inv(diag(d))*U, where U is unit upper triangular with bandwidth (m+1), returns Binv, a sparse symmetric matrix containing the central 2m+1 bands of the inverse of B #Reference: Hutchinson and de Hoog 1985 Binv = sparse(diag(d)); n = rows(U); for i = n:(-1):1 p = min(m, n - i); for l = 1:p for k = 1:p Binv(i, i+l) -= U(i, i+k)*Binv(i + k, i + l); end Binv(i, i) -= U(i, i+l)*Binv(i, i+l); end Binv(i+(1:p), i) = Binv(i, i+(1:p))'; #add the lower triangular elements end endfunction %!shared x,y,ret,p,sigma2,unc_y %! x = [0:0.01:1]'; y = sin(x); %! [ret,p,sigma2,unc_y] = csaps_sel(x,y,x); %!assert (1 - p, 0, 1E-6); %!assert (sigma2, 0, 1E-10); %!assert (ret - y, zeros(size(y)), 1E-4); %!assert (ret, (csaps_sel(x,[y 2*y],x))'(:, 1), 1E-4); %!assert (unc_y, zeros(size(unc_y)), 1E-5); %{ #experiments comparing different selection criteria for recovering a function sampled with standard normal noise -- aicc was consistently better than aic, but otherwise which method does best is problem-specific tic m = 500; #number of replicates available ni = 400; #number of evaluation points ns = [5 10 20 40]; #number of given sample points nk = 100; #number of trials to average over f = @(x) sin(2*pi*x); #function generating the synthetic data mse = nan(4, numel(ns), nk); for i = 1:numel(ns) for k = 1:nk n = ns(i); x = linspace(0, 1, n)(:); y = f(x) + randn(n, m); xi = rand(ni, 1); yt = f(xi); yi = csaps_sel(x,y,xi,[],'vm'); mse(1, i, k) = meansq((yi - yt')(:)); yi = csaps_sel(x,y,xi,[],'aicc'); mse(2, i, k) = meansq((yi - yt')(:)); yi = csaps_sel(x,y,xi,[],'aic'); mse(3, i, k) = meansq((yi - yt')(:)); yi = csaps_sel(x,y,xi,[],'gcv'); mse(4, i, k) = meansq((yi - yt')(:)); endfor endfor msem = mean(mse, 3); toc %} splines/inst/bin_values.m0000644000175000017500000000627412627052101014164 0ustar nirnir## Copyright (C) 2011-2013 Nir Krakauer ## ## 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 . # -*- texinfo -*- ## @deftypefn{Function File}{[@var{x_bin} @var{y_bin} @var{w_bin} @var{n_bin}] =} bin_values(@var{x}, @var{y}, @var{k}) ## ## Average values over ranges of one variable@* ## Given @var{x} (size @var{n}*1) and @var{y} (@var{n}*@var{m}), this function splits the range of @var{x} into up to @var{k} intervals (bins) containing approximately equal numbers of elements, and for each part of the range computes the mean of y. ## ## Any NaN values are removed. ## ## Useful for detecting possible nonlinear dependence of @var{y} on @var{x} and as a preprocessor for spline fitting. ## E.g., to make a plot of the average behavior of y versus x: @code{errorbar(x_bin, y_bin, 1 ./ sqrt(w_bin)); grid on} ## ## Inputs:@* ## @var{x}: @var{n}*1 real array@* ## @var{y}: @var{n}*@var{m} array of values at the coordinates @var{x}@* ## @var{k}: Desired number of bins, @code{floor(sqrt(n))} by default ## ## Outputs:@* ## @var{x_bin}, @var{y_bin}: Mean values by bin (ordered by increasing @var{x}) @* ## @var{w_bin}: Weights (inverse standard error of each element in @var{y_bin}; note: will be NaN or Inf where @var{n_bin} = 1)@* ## @var{n_bin}: Number of elements of @var{x} per bin ## @end deftypefn ## @seealso{csaps, dedup} ## Author: Nir Krakauer function [x_bin y_bin w_bin n_bin] = bin_values(x, y, k=[]) #remove any rows with missing entries notnans = !any (isnan ([x y]) , 2); x = x(notnans); y = y(notnans, :); [n, m] = size(y); #x should be n by 1 if isempty(k) k = floor(sqrt(n)); #reasonable default end if k <= 1 #only a single bin x_bin_mean = mean(x); y_bin_mean = mean(y); w = n / var(y_bin_mean); n_bin = n; return end #arrange values in increasing order of x [x, i] = sort (x); y = y(i, :); #decide where to separate bins bound_inds = 1 + (n-1)*(1:(k-1))/k; bound_x = unique(interp1((1:n)', x, bound_inds)); #assign each point an index corresponding to its bin idx = lookup(bound_x, x); #get number of elements in each bin [ids, ~, j] = unique(idx); #k = numel(ids); #calculate the desired outputs n_bin = accumarray(j, 1); x_bin = accumarray(j, x, [], @mean); y_bin = accumdim(j, y, 1, [], @mean); f = @(x, dim) var(x, [], dim); warning ("off", "Octave:broadcast", "local"); w_bin = n_bin ./ accumdim(j, y, 1, [], f); %!shared x, y, x_bin, y_bin, w_bin, n_bin %! x = [1; 2; 2; 3; 4]; %! y = [0 0; 1 1; 2 1; 3 4; 5 NaN]; %! [x_bin y_bin w_bin n_bin] = bin_values(x, y); %!assert (x_bin, [1; 7/3]); %!assert (y_bin, [0 0; 2 2]); %!assert (!any(isfinite(w_bin(1, :)))); %!assert (w_bin(2, :), [3 1]); %!assert (n_bin, [1; 3]); splines/inst/csape.m0000644000175000017500000002567112627052101013132 0ustar nirnir## Copyright (C) 2000, 2001 Kai Habel ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pp} = } csape (@var{x}, @var{y}, @var{cond}, @var{valc}) ## cubic spline interpolation with various end conditions. ## creates the pp-form of the cubic spline. ## ## the following end conditions as given in @var{cond} are possible. ## @table @asis ## @item 'complete' ## match slopes at first and last point as given in @var{valc} ## @item 'not-a-knot' ## third derivatives are continuous at the second and second last point ## @item 'periodic' ## match first and second derivative of first and last point ## @item 'second' ## match second derivative at first and last point as given in @var{valc} ## @item 'variational' ## set second derivative at first and last point to zero (natural cubic spline) ## @end table ## ## @seealso{ppval, spline} ## @end deftypefn ## Author: Kai Habel ## Date: 23 Nov 2000 ## Algorithms taken from G. Engeln-Muellges, F. Uhlig: ## "Numerical Algorithms with C", Springer, 1996 ## Paul Kienzle, 19 Feb 2001, csape supports now matrix y value ## Nir Krakauer, 21 Nov 2012, fixed a bug with periodic boundary conditions and matrix y (noticed by Ted Rippert); added more tests to verify it won't happen again function pp = csape (x, y, cond, valc) x = x(:); n = length(x); if (n < 3) error("csape requires at least 3 points"); endif ## Check the size and shape of y ndy = ndims (y); szy = size (y); if (ndy == 2 && (szy(1) == n || szy(2) == n)) if (szy(2) == n) a = y.'; else a = y; szy = fliplr (szy); endif else a = shiftdim (reshape (y, [prod(szy(1:end-1)), szy(end)]), 1); endif b = c = zeros (size (a)); h = diff (x); idx = ones (columns(a),1); if (nargin < 3 || strcmp(cond,"complete")) # specified first derivative at end point if (nargin < 4) valc = [0, 0]; endif if (n == 3) warning ("off", "Octave:broadcast", "local"); e = 2 * [h(1) h(1:(end-1))+h(2:end) h(end)]; A = spdiags([[h; 0], e(:), [0; h]], [-1,0,1], n, n); d = diff(a) ./ h; #uses broadcasting if columns(a) > 1 g = 3 * diff(d); A(1, 1) = 2 * h(1); A(1, 2) = h(1); A(n, n) = 2 * h(end); A(end, end-1) = h(end); g = [3*(d(1, :) - valc(1)); g; 3*(valc(2) - d(end, :))]; c = A \ g; else dg = 2 * (h(1:n - 2) .+ h(2:n - 1)); dg(1) = dg(1) - 0.5 * h(1); dg(n - 2) = dg(n-2) - 0.5 * h(n - 1); e = h(2:n - 2); g = 3 * diff (a(2:n,:)) ./ h(2:n - 1,idx)... - 3 * diff (a(1:n - 1,:)) ./ h(1:n - 2,idx); g(1,:) = 3 * (a(3,:) - a(2,:)) / h(2) ... - 3 / 2 * (3 * (a(2,:) - a(1,:)) / h(1) - valc(1)); g(n - 2,:) = 3 / 2 * (3 * (a(n,:) - a(n - 1,:)) / h(n - 1) - valc(2))... - 3 * (a(n - 1,:) - a(n - 2,:)) / h(n - 2); c(2:n - 1,:) = spdiags([[e(:);0],dg,[0;e(:)]],[-1,0,1],n-2,n-2) \ g; c(1,:) = (3 / h(1) * (a(2,:) - a(1,:)) - 3 * valc(1) - c(2,:) * h(1)) / (2 * h(1)); c(n,:) = - (3 / h(n - 1) * (a(n,:) - a(n - 1,:)) - 3 * valc(2) + c(n - 1,:) * h(n - 1)) / (2 * h(n - 1)); end b(1:n - 1,:) = diff (a) ./ h(1:n - 1, idx)... - h(1:n - 1,idx) / 3 .* (c(2:n,:) + 2 * c(1:n - 1,:)); d = diff (c) ./ (3 * h(1:n - 1, idx)); elseif (strcmp(cond,"variational") || strcmp(cond,"second")) if ((nargin < 4) || strcmp(cond,"variational")) ## set second derivatives at end points to zero valc = [0, 0]; endif c(1,:) = valc(1) / 2; c(n,:) = valc(2) / 2; g = 3 * diff (a(2:n,:)) ./ h(2:n - 1, idx)... - 3 * diff (a(1:n - 1,:)) ./ h(1:n - 2, idx); g(1,:) = g(1,:) - h(1) * c(1,:); g(n - 2,:) = g(n-2,:) - h(n - 1) * c(n,:); if( n == 3) dg = 2 * h(1); c(2:n - 1,:) = g / dg; else dg = 2 * (h(1:n - 2) .+ h(2:n - 1)); e = h(2:n - 2); c(2:n - 1,:) = spdiags([[e(:);0],dg,[0;e(:)]],[-1,0,1],n-2,n-2) \ g; end b(1:n - 1,:) = diff (a) ./ h(1:n - 1,idx)... - h(1:n - 1,idx) / 3 .* (c(2:n,:) + 2 * c(1:n - 1,:)); d = diff (c) ./ (3 * h(1:n - 1, idx)); elseif (strcmp(cond,"periodic")) h = [h; h(1)]; ## XXX FIXME XXX --- the following gives a smoother periodic transition: ## a(n,:) = a(1,:) = ( a(n,:) + a(1,:) ) / 2; a(n,:) = a(1,:); tmp = diff (shift ([a; a(2,:)], -1)); g = 3 * tmp(1:n - 1,:) ./ h(2:n,idx)... - 3 * diff (a) ./ h(1:n - 1,idx); if (n > 3) dg = 2 * (h(1:n - 1) .+ h(2:n)); e = h(2:n - 1); ## Use Sherman-Morrison formula to extend the solution ## to the cyclic system. See Numerical Recipes in C, pp 73-75 gamma = - dg(1); dg(1) -= gamma; dg(end) -= h(1) * h(1) / gamma; z = spdiags([[e(:);0],dg,[0;e(:)]],[-1,0,1],n-1,n-1) \ ... [[gamma; zeros(n-3,1); h(1)],g]; fact = (z(1,2:end) + h(1) * z(end,2:end) / gamma) / ... (1.0 + z(1,1) + h(1) * z(end,1) / gamma); c(2:n,:) = z(:,2:end) - z(:,1) * fact; endif c(1,:) = c(n,:); b = diff (a) ./ h(1:n - 1,idx)... - h(1:n - 1,idx) / 3 .* (c(2:n,:) + 2 * c(1:n - 1,:)); b(n,:) = b(1,:); d = diff (c) ./ (3 * h(1:n - 1, idx)); d(n,:) = d(1,:); elseif (strcmp(cond,"not-a-knot")) g = zeros(n - 2,columns(a)); g(1,:) = 3 / (h(1) + h(2)) * (a(3,:) - a(2,:)... - h(2) / h(1) * (a(2,:) - a(1,:))); g(n - 2,:) = 3 / (h(n - 1) + h(n - 2)) *... (h(n - 2) / h(n - 1) * (a(n,:) - a(n - 1,:)) -... (a(n - 1,:) - a(n - 2,:))); if (n > 4) g(2:n - 3,:) = 3 * diff (a(3:n - 1,:)) ./ h(3:n - 2,idx)... - 3 * diff (a(2:n - 2,:)) ./ h(2:n - 3,idx); dg = 2 * (h(1:n - 2) .+ h(2:n - 1)); dg(1) = dg(1) - h(1); dg(n - 2) = dg(n-2) - h(n - 1); ldg = udg = h(2:n - 2); udg(1) = udg(1) - h(1); ldg(n - 3) = ldg(n-3) - h(n - 1); c(2:n - 1,:) = spdiags([[ldg(:);0],dg,[0;udg(:)]],[-1,0,1],n-2,n-2) \ g; elseif (n == 4) dg = [h(1) + 2 * h(2); 2 * h(2) + h(3)]; ldg = h(2) - h(3); udg = h(2) - h(1); c(2:n - 1,:) = spdiags([[ldg(:);0],dg,[0;udg(:)]],[-1,0,1],n-2,n-2) \ g; else # n == 3 dg= [h(1) + 2 * h(2)]; c(2:n - 1,:) = g/dg(1); endif c(1,:) = c(2,:) + h(1) / h(2) * (c(2,:) - c(3,:)); c(n,:) = c(n - 1,:) + h(n - 1) / h(n - 2) * (c(n - 1,:) - c(n - 2,:)); b = diff (a) ./ h(1:n - 1, idx)... - h(1:n - 1, idx) / 3 .* (c(2:n,:) + 2 * c(1:n - 1,:)); d = diff (c) ./ (3 * h(1:n - 1, idx)); else msg = sprintf("unknown end condition: %s",cond); error (msg); endif d = d(1:n-1,:); c=c(1:n-1,:); b=b(1:n-1,:); a=a(1:n-1,:); pp = mkpp (x, cat (2, d'(:), c'(:), b'(:), a'(:)), szy(1:end-1)); endfunction %!shared x,x2,y,cond,pp,h,valc %! x = linspace(0,2*pi,5); y = sin(x); x2 = linspace(0,2*pi,16); %!assert (ppval(csape(x,y),x), y, 10*eps); %!assert (ppval(csape(x,y),x'), y', 10*eps); %!assert (ppval(csape(x',y'),x'), y', 10*eps); %!assert (ppval(csape(x',y'),x), y, 10*eps); %!assert (ppval(csape(x,[y;y]),x), ... %! [ppval(csape(x,y),x);ppval(csape(x,y),x)], 10*eps) %!assert (ppval(csape(x,[y;y]),x2), ... %! [ppval(csape(x,y),x2);ppval(csape(x,y),x2)], 10*eps) %!test cond='complete'; %!assert (ppval(csape(x,y,cond),x), y, 10*eps); %!assert (ppval(csape(x,y,cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x), y, 10*eps); %!assert (ppval(csape(x,[y;y],cond),x), ... %! [ppval(csape(x,y,cond),x);ppval(csape(x,y,cond),x)], 10*eps) %!assert (ppval(csape(x,[y;y],cond),x2), ... %! [ppval(csape(x,y,cond),x2);ppval(csape(x,y,cond),x2)], 10*eps) %!test cond='variational'; %!assert (ppval(csape(x,y,cond),x), y, 10*eps); %!assert (ppval(csape(x,y,cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x), y, 10*eps); %!assert (ppval(csape(x,[y;y],cond),x), ... %! [ppval(csape(x,y,cond),x);ppval(csape(x,y,cond),x)], 10*eps) %!assert (ppval(csape(x,[y;y],cond),x2), ... %! [ppval(csape(x,y,cond),x2);ppval(csape(x,y,cond),x2)], 10*eps) %!test cond='second'; %!assert (ppval(csape(x,y,cond),x), y, 10*eps); %!assert (ppval(csape(x,y,cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x), y, 10*eps); %!assert (ppval(csape(x,[y;y],cond),x), ... %! [ppval(csape(x,y,cond),x);ppval(csape(x,y,cond),x)], 10*eps) %!assert (ppval(csape(x,[y;y],cond),x2), ... %! [ppval(csape(x,y,cond),x2);ppval(csape(x,y,cond),x2)], 10*eps) %!test cond='periodic'; %!assert (ppval(csape(x,y,cond),x), y, 10*eps); %!assert (ppval(csape(x,y,cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x), y, 10*eps); %!assert (ppval(csape(x,[y;y],cond),x), ... %! [ppval(csape(x,y,cond),x);ppval(csape(x,y,cond),x)], 10*eps) %!assert (ppval(csape(x,[y;y],cond),x2), ... %! [ppval(csape(x,y,cond),x2);ppval(csape(x,y,cond),x2)], 10*eps) %!test cond='not-a-knot'; %!assert (ppval(csape(x,y,cond),x), y, 10*eps); %!assert (ppval(csape(x,y,cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x'), y', 10*eps); %!assert (ppval(csape(x',y',cond),x), y, 10*eps); %!assert (ppval(csape(x,[y;y],cond),x), ... %! [ppval(csape(x,y,cond),x);ppval(csape(x,y,cond),x)], 10*eps) %!assert (ppval(csape(x,[y;y],cond),x2), ... %! [ppval(csape(x,y,cond),x2);ppval(csape(x,y,cond),x2)], 10*eps) %!assert (ppval(csape(x(1:4),y(1:4),cond),x(1:4)), y(1:4), 10*eps); %!assert (ppval(csape(x(1:4)',y(1:4)',cond),x(1:4)), y(1:4), 10*eps); %!test cond='complete'; %! h = pi/4; n = 3; x = linspace(0,(n-1)*h,n); y = sin(x); valc = cos([x(1) x(end)]); pp = csape(x, y, cond, valc); %!assert (ppval(csape(x,[y;y],cond, valc),x), ... %! repmat(ppval(pp, x), [2 1]), 10*eps) %!assert (polyval(pp.coefs(1, :), [0 h]), y(1:2), 10*eps) %!assert (polyval(pp.coefs(2, :), [0 h]), y(2:3), 10*eps) %!assert (polyval([3*pp.coefs(1, 1) 2*pp.coefs(1, 2) pp.coefs(1, 3)], 0), valc(1), 10*eps) %!assert (polyval([3*pp.coefs(2, 1) 2*pp.coefs(2, 2) pp.coefs(2, 3)], h), valc(2), 10*eps) %!assert (polyval([3*pp.coefs(1, 1) 2*pp.coefs(1, 2) pp.coefs(1, 3)], h), polyval([3*pp.coefs(2, 1) 2*pp.coefs(2, 2) pp.coefs(2, 3)], 0), 10*eps) %!assert (polyval([6*pp.coefs(1, 1) 2*pp.coefs(1, 2)], h), polyval([6*pp.coefs(2, 1) 2*pp.coefs(2, 2)], 0), 10*eps) splines/inst/csaps.m0000644000175000017500000001660112627052101013141 0ustar nirnir## Copyright (C) 2012-2013 Nir Krakauer ## ## 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 2 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 . ## -*- texinfo -*- ## @deftypefn{Function File}{[@var{yi} @var{p} @var{sigma2} @var{unc_yi}] =} csaps(@var{x}, @var{y}, @var{p}, @var{xi}, @var{w}=[]) ## @deftypefnx{Function File}{[@var{pp} @var{p} @var{sigma2}] =} csaps(@var{x}, @var{y}, @var{p}, [], @var{w}=[]) ## ## Cubic spline approximation (smoothing)@* ## approximate [@var{x},@var{y}], weighted by @var{w} (inverse variance; if not given, equal weighting is assumed), at @var{xi} ## ## The chosen cubic spline with natural boundary conditions @var{pp}(@var{x}) minimizes @var{p} Sum_i @var{w}_i*(@var{y}_i - @var{pp}(@var{x}_i))^2 + (1-@var{p}) Int @var{pp}''(@var{x}) d@var{x} ## ## Outside the range of @var{x}, the cubic spline is a straight line ## ## @var{x} and @var{w} should be n by 1 in size; @var{y} should be n by m; @var{xi} should be k by 1; the values in @var{x} should be distinct and in ascending order; the values in @var{w} should be nonzero ## ## @table @asis ## @item @var{p}=0 ## maximum smoothing: straight line ## @item @var{p}=1 ## no smoothing: interpolation ## @item @var{p}<0 or not given ## an intermediate amount of smoothing is chosen (such that the smoothing term and the interpolation term are of the same magnitude) ## (csaps_sel provides other methods for automatically selecting the smoothing parameter @var{p}.) ## @end table ## ## @var{sigma2} is an estimate of the data error variance, assuming the smoothing parameter @var{p} is realistic ## ## @var{unc_yi} is an estimate of the standard error of the fitted curve(s) at the @var{xi}. ## Empty if @var{xi} is not provided. ## ## Reference: Carl de Boor (1978), A Practical Guide to Splines, Springer, Chapter XIV ## ## @end deftypefn ## @seealso{spline, csapi, ppval, dedup, bin_values, csaps_sel} ## Author: Nir Krakauer function [ret,p,sigma2,unc_yi]=csaps(x,y,p,xi,w) warning ("off", "Octave:broadcast", "local"); if(nargin < 5) w = []; if(nargin < 4) xi = []; if(nargin < 3) p = []; endif endif endif if(columns(x) > 1) x = x'; y = y'; w = w'; endif if any (isnan ([x y w](:)) ) error('NaN values in inputs; pre-process to remove them') endif h = diff(x); if !all(h > 0) && !all(h < 0) error('x must be strictly monotone; pre-process to achieve this') endif [n m] = size(y); #should also be that n = numel(x); if isempty(w) w = ones(n, 1); end R = spdiags([h(2:end) 2*(h(1:end-1) + h(2:end)) h(1:end-1)], [-1 0 1], n-2, n-2); #this is the correct expression QT = spdiags([1 ./ h(1:end-1) -(1 ./ h(1:end-1) + 1 ./ h(2:end)) 1 ./ h(2:end)], [0 1 2], n-2, n); ## if not given, choose p so that trace(6*(1-p)*QT*diag(1 ./ w)*QT') = trace(p*R) if isempty(p) || (p < 0) r = full(6*trace(QT*diag(1 ./ w)*QT') / trace(R)); p = r ./ (1 + r); endif ## solve for the scaled second derivatives u and for the function values a at the knots (if p = 1, a = y; if p = 0, cc(:) = dd(:) = 0) ## QT*y can also be written as (y(3:n, :) - y(2:(n-1), :)) ./ h(2:end) - (y(2:(n-1), :) - y(1:(n-2), :)) ./ h(1:(end-1)) u = (6*(1-p)*QT*diag(1 ./ w)*QT' + p*R) \ (QT*y); a = y - 6*(1-p)*diag(1 ./ w)*QT'*u; ## derivatives for the piecewise cubic spline aa = bb = cc = dd = zeros (n+1, m); aa(2:end, :) = a; cc(3:n, :) = 6*p*u; #second derivative at endpoints is 0 [natural spline] dd(2:n, :) = diff(cc(2:(n+1), :)) ./ h; bb(2:n, :) = diff(a) ./ h - (h/3) .* (cc(2:n, :) + cc(3:(n+1), :)/2); ## note: add knots to either end of spline pp-form to ensure linear extrapolation xminus = x(1) - eps(x(1)); xplus = x(end) + eps(x(end)); x = [xminus; x; xplus]; slope_minus = bb(2, :); slope_plus = bb(n, :) + cc(n, :)*h(n-1) + (dd(n, :)/2)*h(n-1)^2; bb(1, :) = slope_minus; #linear extension of splines bb(n + 1, :) = slope_plus; aa(1, :) = a(1, :) - eps(x(1))*bb(1, :); ret = mkpp (x, cat (2, dd'(:)/6, cc'(:)/2, bb'(:), aa'(:)), m); if ~isempty (xi) ret = ppval (ret, xi); endif if (isargout (4) && isempty (xi)) unc_yi = []; endif if isargout (3) || (isargout (4) && ~isempty (xi)) if p == 1 #interpolation assumes no error in the given data sigma2 = 0; if isargout (4) && ~isempty (xi) unc_yi = zeros(numel(xi), 1); endif break endif [U D V] = svd(diag(1 ./ sqrt(w))*QT'*sqrtm(inv(R)), 0); D = diag(D).^2; #influence matrix for given p A = speye(n) - U * diag(D ./ (D + (p / (6*(1-p))))) * U'; A = diag(1 ./ sqrt(w)) * A * diag(sqrt(w)); #rescale to original units; a = A*y MSR = mean(w .* (y - (A*y)) .^ 2); #mean square residual Ad = diag(A); At = trace(A); sigma2 = mean(MSR(:)) * (n / (n-At)); #estimated data error variance (wahba83) if isargout (4) && ~isempty (xi) ni = numel (xi); #dependence of spline values on each given point (to compute uncertainty) C = 6 * p * full ((6*(1-p)*QT*diag(1 ./ w)*QT' + p*R) \ QT); #cc(3:n, :) = C*y [sparsity is lost] D = diff ([zeros(n, 1) C' zeros(n, 1)]') ./ h; #dd(2:n, :) = D*y B = diff (A) ./ h - (h/3) .* ([zeros(n, 1) C']' + [C' zeros(n, 1)]' / 2); #bb(2:n, :) = B*y #add end-points C = [zeros(n, 2) C' zeros(n, 1)]'; D = [zeros(n, 1) D' zeros(n, 1)]'; B = [B(1, :)' B' B(end, :)' + C(n, :)'*h(n-1) + (D(n, :)'/2)*h(n-1)^2]'; A = [A(1, :)'-eps(x(1))*B(1, :)' A']'; #sum the squared dependence on each data value y at each requested point xi unc_yi = zeros (ni, 1); for i = 1:n unc_yi += (ppval (mkpp (x, cat (2, D(:, i)/6, C(:, i)/2, B(:, i), A(:, i))), xi(:))) .^ 2; endfor unc_yi = sqrt (sigma2 * unc_yi); #not exactly the same as unc_y as calculated in csaps_sel even if xi = x, but fairly close endif endif endfunction %!shared x,y, xi %! x = ([1:10 10.5 11.3])'; y = sin(x); xi = linspace(min(x), max(x), 30); %!assert (csaps(x,y,1,x), y, 10*eps); %!assert (csaps(x,y,1,x'), y', 10*eps); %!assert (csaps(x',y',1,x'), y', 10*eps); %!assert (csaps(x',y',1,x), y, 10*eps); %!assert (csaps(x,[y 2*y],1,x)', [y 2*y], 10*eps); %!assert (csaps(x,y,1,xi), ppval(csape(x, y, "variational"), xi), eps); %!assert (csaps(x,y,0,xi), polyval(polyfit(x, y, 1), xi), 10*eps); %{ test weighted smoothing: n = 500; a = 0; b = pi; f = @(x) sin(x); x = a + (b-a)*sort(rand(n, 1)); w = rand(n, 1); y = f(x) + randn(n, 1) ./ sqrt(w); xi = linspace(a, b, n)'; yi_target = f(xi); [~,p_sel] = csaps_sel(x, y, xi, w, 1); [yi,~,sigma2,unc_yi] = csaps(x,y,p_sel,xi,w); rmse = rms((yi - yi_target)); rmse_weighted = rms((yi - yi_target) ./ unc_yi); #worse results without the (correct) weighting: [~,p_sel] = csaps_sel(x, y, xi, []); [yi,~,sigma2,unc_yi] = csaps(x,y,p_sel,xi,[]); rmse_u = rms((yi - yi_target)); rmse_u_weighted = rms((yi - yi_target) ./ unc_yi); %} splines/inst/catmullrom.m0000644000175000017500000000355012627052101014206 0ustar nirnir## Copyright (C) 2008 Carlo de Falco ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pp}} = catmullrom( @var{x},@ ## @var{f}, @var{v}) ## ## Returns the piecewise polynomial form of the Catmull-Rom cubic ## spline interpolating @var{f} at the points @var{x}. ## If the input @var{v} is supplied it will be interpreted as the ## values of the tangents at the extremals, if it is ## missing, the values will be computed from the data via one-sided ## finite difference formulas. See the wikipedia page for "Cubic ## Hermite spline" for a description of the algorithm. ## ## @seealso{ppval} ## @end deftypefn function pp = catmullrom(x,f,v) if ( nargin < 2 ) print_usage(); endif h00 = [2 -3 0 1]; h10 = [1 -2 1 0]; h01 = [-2 3 0 0]; h11 = [1 -1 0 0]; h = diff(x(:)'); p0 = f(:)'(1:end-1); p1 = f(:)'(2:end); if (nargin < 3) v(1) = (p1(1)-p0(1))./h(1); v(2) = (p1(end)-p0(end))./h(end); endif m = (p1(2:end)-p0(1:end-1))./(h(2:end)+h(1:end-1)); m0 = [v(1) m]; m1 = [m v(2)]; for ii = 1:4 coeff(:,ii) = ((h00(ii)*p0 + h10(ii)*h.*m0 +... h01(ii)*p1 + h11(ii)*h.*m1 )./h.^(4-ii))' ; end pp = mkpp (x, coeff); endfunction splines/inst/fnplt.m0000644000175000017500000000336612627052101013157 0ustar nirnir## Copyright (C) 2000 Kai Habel ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} { } fnplt (@var{pp}, '@var{plt}') ## plots spline ## ## @seealso{ppval, spline, csape} ## @end deftypefn ## Author: Kai Habel ## Date: 3. dec 2000 ## 2001-02-19 Paul Kienzle ## * use pp.x rather than just x in linspace; add plt parameter ## * return points instead of plotting them if desired ## * also plot control points ## * added demo function [x, y] = fnplt (pp, plt) if (nargin < 1 || nargin > 2) print_usage; endif if (nargin < 2) plt = "r;;"; endif xi = linspace(min(pp.x),max(pp.x),256)'; pts = ppval(pp,xi); if nargout == 2 x = xi; y = pts; elseif nargout == 1 x = [xi, pts]; else plot(xi,pts,plt,pp.x,ppval(pp,pp.x),"bx;;"); endif endfunction %!demo %! x = [ 0; sort(rand(25,1)); 1 ]; %! pp = csape (x, sin (2*pi*3*x), 'periodic'); %! axis([0,1,-2,2]); %! title('Periodic spline reconstruction of randomly sampled sine'); %! fnplt (pp,'r;reconstruction;'); %! t=linspace(0,1,100); y=sin(2*pi*3*t); %! hold on; plot(t,y,'g;ideal;'); hold off; %! axis; title(""); splines/inst/fnval.m0000644000175000017500000000071512627052101013135 0ustar nirnir## Author: Paul Kienzle ## This program is granted to the public domain. ## r = fnval(pp,x) or r = fnval(x,pp) ## Compute the value of the piece-wise polynomial pp at points x. function r = fnval(a,b,left) if nargin == 2 || (nargin == 3 && left == 'l' && left == 'r') # XXX FIXME XXX ignoring left continuous vs. right continuous option if isstruct(a), r=ppval(a,b); else r=ppval(b,a); end else print_usage; end end splines/inst/csapi.m0000644000175000017500000000215112627052101013122 0ustar nirnir## Copyright (C) 2000 Kai Habel ## ## 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 . ## -*- texinfo -*- ## @deftypefn {Function File} {@var{pp} = } csapi (@var{x}, @var{y}) ## @deftypefnx {Function File} {@var{yi} = } csapi (@var{x}, @var{y}, @var{xi}) ## cubic spline interpolation ## ## @seealso{ppval, spline, csape} ## @end deftypefn ## Author: Kai Habel ## Date: 3. dec 2000 function ret = csapi (x, y, xi) ret = csape(x,y,'not-a-knot'); if (nargin == 3) ret = ppval(ret,xi); endif endfunction splines/inst/dedup.m0000644000175000017500000000531112627052101013125 0ustar nirnir## Copyright (C) 2013 Nir Krakauer ## ## 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 . ## -*- texinfo -*- ## @deftypefn{Function File}{[@var{x_new} @var{y_new} @var{w_new}] =} dedup(@var{x}, @var{y}, @var{w}, @var{tol}, @var{nan_remove}=true) ## ## De-duplication and sorting to facilitate spline smoothing@* ## Points are sorted in ascending order of @var{x}, with each set of duplicates (values with the same @var{x}, within @var{tol}) replaced by a weighted average. ## Any NaN values are removed (if the flag @var{nan_remove} is set). ## ## Useful, for example, as a preprocessor to spline smoothing ## ## Inputs:@* ## @var{x}: @var{n}*1 real array@* ## @var{y}: @var{n}*@var{m} array of values at the coordinates @var{x}@* ## @var{w}: @var{n}*1 array of positive weights (inverse error variances); @code{ones(size(x))} by default@* ## @var{tol}: if the difference between two @var{x} values is no more than this scalar, merge them; 0 by default ## ## Outputs: ## De-duplicated and sorted @var{x}, @var{y}, @var{w} ## @end deftypefn ## @seealso{csaps, bin_values} ## Author: Nir Krakauer function [x, y, w] = dedup(x, y, w=ones(size(x)), tol=0, nan_remove=true) warning ("off", "Octave:broadcast", "local"); if isempty(w) w = ones(size(x)); endif if isempty(tol) tol = 0; endif if nan_remove #remove any rows with missing entries notnans = !any (isnan ([x y w]) , 2); x = x(notnans); y = y(notnans, :); w = w(notnans); endif [x,i] = sort(x); y = y(i, :); w = w(i); h = diff(x); if any(h <= tol) hh = ones(size(x)); hh(2:end) = cumsum(h > tol) + 1; #any elements tol or less apart are placed in the same equivalence class #replace original points with equivalence classes, using weighted averages wnew = accumarray(hh, w); x = accumarray(hh, x .* w) ./ wnew; y = accumdim(hh, y .* w, 1) ./ wnew; w = wnew; endif %!shared x, y, w %! x = [1; 2; 2; 3; 4]; %! y = [0 0; 1 1; 2 1; 3 4; 5 NaN]; %! w = [1; 0.1; 1; 0.5; 1]; %!assert (nthargout(1:3, @dedup, x, y, ones(size(x))), nthargout(1:3, @dedup, x, y)) %! [x y w] = dedup(x, y, w); %!assert (x, [1; 2; 3]); %!assert (y, [0 0; 21/11 1; 3 4], 10*eps); %!assert (w, [1; 1.1; 0.5]); splines/inst/tps_val_der.m0000644000175000017500000001014512627052101014327 0ustar nirnir## Copyright (C) 2015 Nir Krakauer ## ## 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 . ## -*- texinfo -*- ## @deftypefn{Function File}{[@var{dyi}] =} tps_val_der(@var{x}, @var{coefs}, @var{xi}, @var{vectorize}=true ) ## ## Evaluates the first derivative of a thin plate spline at given points @* ## @var{xi} ## ## @var{coefs} should be the vector of fitted coefficients returned from @code{tpaps(x, y, [p])} ## ## @var{x} should be @var{n} by @var{d} in size, where @var{n} is the number of points and @var{d} the number of dimensions; @var{coefs} should be (@var{n} + @var{d} + 1) by 1; @var{xi} should be @var{k} by @var{d} ## ## The logical argument @var{vectorize} controls whether @var{k} by @var{n} by @var{d} intermediate arrays are formed to speed up computation (the default) or whether looping is used to economize on memory ## ## The returned @var{dyi} will be @var{k} by @var{d}, containing the first partial derivatives of the thin plate spline at @var{xi} ## ## ## Example usages: ## @example ## x = ([1:10 10.5 11.3])'; y = sin(x); dy = cos(x); xi = (0:0.1:12)'; ## coefs = tpaps(x, y, 0.5); ## [dyi] = tps_val_der(x,coefs,xi); ## subplot(1, 1, 1) ## plot(x, dy, 's', xi, dyi) ## legend('original', 'tps') ## @end example ## ## @example ## x = rand(100, 2)*2 - 1; ## y = x(:, 1) .^ 2 + x(:, 2) .^ 2; ## [x1 y1] = meshgrid((-1:0.2:1)', (-1:0.2:1)'); ## xi = [x1(:) y1(:)]; ## coefs = tpaps(x, y, 1); ## dyio = [2*x1(:) 2*y1(:)]; ## [dyi] = tps_val_der(x,coefs,xi); ## subplot(2, 2, 1) ## contourf(x1, y1, reshape(dyio(:, 1), 11, 11)); colorbar ## title('original x1 partial derivative') ## subplot(2, 2, 2) ## contourf(x1, y1, reshape(dyi(:, 1), 11, 11)); colorbar ## title('tps x1 partial derivative') ## subplot(2, 2, 3) ## contourf(x1, y1, reshape(dyio(:, 2), 11, 11)); colorbar ## title('original x2 partial derivative') ## subplot(2, 2, 4) ## contourf(x1, y1, reshape(dyi(:, 2), 11, 11)); colorbar ## title('tps x2 partial derivative') ## @end example ## ## See the documentation to @code{tpaps} for more information ## ## @end deftypefn ## @seealso{tpaps, tpaps_val, tps_val_der} ## Author: Nir Krakauer function [dyi]=tps_val_der(x,coefs,xi,vectorize=true) [n d] = size(x); #d: number of dimensions; n: number of points k = size(xi, 1); #number of points for which to find the spline derivative value #derivative of the spline Green's function, divided by radial distance dG_scaled = @(r) merge(r == 0, 0, 1 + 2 .* log(r)); a = coefs(1:n); b = coefs((n+1):end); dyi = ones(k, 1) * b(2:end)'; #derivatives of linear part if vectorize dists = reshape(xi, k, 1, d) - reshape(x, 1, n, d); dist = sqrt(sumsq(dists, 3)); #Euclidian distance between points in d-dimensional space dyi += squeeze(sum(reshape(a, 1, n) .* dG_scaled(dist) .* dists, 2)); else for i = 1:k for l = 1:n dists = xi(i, :) - x(l, :); dist = sqrt(sumsq(dists)); dyi(i, :) += a(l) * dG_scaled(dist) * dists; endfor endfor endif endfunction #check with linear functions (derivatives should be constant) %!shared a,b,x,y,x1,x2,y1,c,dy,dy0 %! a = 2; b = -3; x = ([1:2:10 10.5 11.3])'; y = a*x; %! c = tpaps(x,y,1); %!assert (a*ones(size(x)), tps_val_der(x,c,x), 1E3*eps); %! [x1 x2] = meshgrid(x, x); %! y1 = a*x1+b*x2; %! c = tpaps([x1(:) x2(:)],y1(:),0.5); %! dy = tps_val_der([x1(:) x2(:)],c,[x1(:) x2(:)]); %! dy0 = tps_val_der([x1(:) x2(:)],c,[x1(:) x2(:)],false); %!assert (a*ones(size(x1(:))), dy(:, 1), 1E3*eps); %!assert (b*ones(size(x2(:))), dy(:, 2), 1E3*eps); %!assert (dy0, dy, 1E3*eps); splines/inst/tps_val.m0000644000175000017500000000614112627052101013476 0ustar nirnir## Copyright (C) 2013 Nir Krakauer ## ## 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 2 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 . ## -*- texinfo -*- ## @deftypefn{Function File}{[@var{yi}] =} tps_val(@var{x}, @var{coefs}, @var{xi}, @var{vectorize}=true) ## ## Evaluates a thin plate spline at given points @* ## @var{xi} ## ## @var{coefs} should be the vector of fitted coefficients returned from @code{tpaps(x, y, [p])} ## ## @var{x} should be @var{n} by @var{d} in size, where @var{n} is the number of points and @var{d} the number of dimensions; @var{coefs} should be @var{n} + @var{d} + 1 by 1; @var{xi} should be @var{k} by @var{d} ## ## The logical argument @var{vectorize} controls whether an @var{k} by @var{n} by @var{d} intermediate array is formed to speed up computation (the default) or whether looping is used to economize on memory ## ## The returned @var{yi} will be @var{k} by 1 ## ## See the documentation to @code{tpaps} for more information ## ## @end deftypefn ## @seealso{tpaps, tps_val_der} ## Author: Nir Krakauer function [yi]=tps_val(x,coefs,xi,vectorize=true) [n d] = size(x); #d: number of dimensions; n: number of points k = size(xi, 1); #number of points for which to find the spline function value #form of the Green's function for solutions G = @(r) merge(r == 0, 0, r .^ 2 .* log(r)); a = coefs(1:n); b = coefs((n+1):end); yi = [ones(k, 1) xi] * b; if vectorize if d == 1 yi = yi + G(abs(x' - xi)) * a; else yi = yi + G(sqrt(sumsq((reshape(x, 1, n, d) - reshape(xi, k, 1, d)), 3))) * a; endif else dist = @(x1, x2) norm(x2 - x1, 2, "rows"); #Euclidian distance between points in d-dimensional space warn_state = warning ("query", "Octave:broadcast").state; warning ("off", "Octave:broadcast"); #turn off warning message for automatic broadcasting when dist is called unwind_protect if k > n ##choose from either of two ways of computing the values of the thin plate spline at xi for i = 1:n yi = yi + a(i)*G(dist(x(i, :), xi)); endfor else for i = 1:k yi(i) = yi(i) + dot(a, G(dist(x, xi(i, :)))); endfor endif unwind_protect_cleanup warning (warn_state, "Octave:broadcast"); end_unwind_protect endif endfunction %!shared x,y,c,xi %! x = ([1:10 10.5 11.3])'; y = sin(x); %! c = tpaps(x,y,1); %!assert (tpaps(x,y,1,x), tps_val(x,c,x)); %! x = rand(100, 2)*2 - 1; %! y = x(:, 1) .^ 2 + x(:, 2) .^ 2; %! c = tpaps(x,y,1); %!assert (tpaps(x,y,1,x), tps_val(x,c,x), 100*eps); %! xi = rand(30, 2); %!assert (tps_val(x,c,x,true), tps_val(x,c,x,false), 100*eps); splines/inst/tpaps.m0000644000175000017500000001255212627052101013160 0ustar nirnir## Copyright (C) 2013 Nir Krakauer ## ## 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 2 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 . ## -*- texinfo -*- ## @deftypefn{Function File}{[@var{yi} @var{p}] =} tpaps(@var{x}, @var{y}, @var{p}, @var{xi}) ## @deftypefnx{Function File}{[@var{coefs} @var{p}] =} tpaps(@var{x}, @var{y}, @var{p}, []) ## ## Thin plate smoothing of scattered values in multi-D @* ## approximately interpolate [@var{x},@var{y}] at @var{xi} ## ## The chosen thin plate spline minimizes the sum of squared deviations from the given points plus a penalty term proportional to the curvature of the spline function ## ## @var{x} should be @var{n} by @var{d} in size, where @var{n} is the number of points and @var{d} the number of dimensions; @var{y} and @var{w} should be @var{n} by 1; @var{xi} should be @var{k} by @var{d}; the points in @var{x} should be distinct ## ## @table @asis ## @item @var{p}=0 ## maximum smoothing: flat surface ## @item @var{p}=1 ## no smoothing: interpolation ## @item @var{p}<0 or not given ## an intermediate amount of smoothing is chosen (such that the smoothing term and the interpolation term are of the same magnitude) ## @end table ## ## If @var{xi} is not specified, returns a vector @var{coefs} of the @var{n} + @var{d} + 1 fitted thin plate spline coefficients. ## Given @var{coefs}, the value of the thin-plate spline at any @var{xi} can be determined with @code{tps_val} ## ## Note: Computes the pseudoinverse of an @var{n} by @var{n} matrix, so not recommended for very large @var{n} ## ## Example usages: ## @example ## x = ([1:10 10.5 11.3])'; y = sin(x); xi = (0:0.1:12)'; ## yi = tpaps(x, y, 0.5, xi); ## plot(x, y, xi, yi) ## @end example ## ## @example ## x = rand(100, 2)*2 - 1; ## y = x(:, 1) .^ 2 + x(:, 2) .^ 2; ## scatter(x(:, 1), x(:, 2), 10, y, "filled") ## [x1 y1] = meshgrid((-1:0.2:1)', (-1:0.2:1)'); ## xi = [x1(:) y1(:)]; ## yi = tpaps(x, y, 1, xi); ## contourf(x1, y1, reshape(yi, 11, 11)) ## @end example ## ## Reference: ## David Eberly (2011), Thin-Plate Splines, www.geometrictools.com/Documentation/ThinPlateSplines.pdf ## Bouhamidi, A. (2005) Weighted thin plate splines, Analysis and Applications, 3: 297-324 ## ## @end deftypefn ## @seealso{csaps, tps_val, tps_val_der} ## Author: Nir Krakauer function [ret, p]=tpaps(x,y,p,xi) if(nargin < 4) xi = []; if(nargin < 3) || p < 0 p = []; endif endif [n d] = size(x); #d: number of dimensions; n: number of points [y should be n*1] dist = @(x1, x2) norm(x2 - x1, 2, "rows"); #Euclidian distance between points in d-dimensional space #form of the Green's function for solutions G = @(r) merge(r == 0, 0, r .^ 2 .* log(r)); N = [ones(n, 1) x]; if p == 0 #infinite regularization (no curvature allowed), solution is a regression plane b = N \ y; a = zeros(n, 1); else #coefficient matrices #need pairwise distances between points M = zeros(n); warn_state = warning ("query", "Octave:broadcast").state; warning ("off", "Octave:broadcast"); #turn off warning message for automatic broadcasting when dist is called unwind_protect for i = 1:(n-1) #M is symmetric, so only need to compute half M(i, (i+1):n) = G(dist(x(i, :), x((i+1):n, :))); endfor unwind_protect_cleanup warning (warn_state, "Octave:broadcast"); end_unwind_protect M = M + M'; if isempty(p) #choose an intermediate value for the regularization parameter lambda = mean(spdiags(M, 1:min(n, 3))(:)); p = 1 / (lambda + 1); else #use the given value lambda = (1 - p) / p; endif M = M + lambda*eye(n); #add regularization term M_inv = pinv(M); b = pinv(N' * M_inv * N) * N' * M_inv * y; a = M_inv * (y - N*b); endif if isempty(xi) #return the coefficients ret = [a' b']'; else #return the thin plate spline values at xi k = size(xi, 1); ret = [ones(k, 1) xi] * b; if p ~= 0 warn_state = warning ("query", "Octave:broadcast").state; warning ("off", "Octave:broadcast"); #turn off warning message for automatic broadcasting when dist is called unwind_protect if k > n ##choose from either of two ways of computing the values of the thin plate spline at xi for i = 1:n ret = ret + a(i)*G(dist(x(i, :), xi)); endfor else for i = 1:k ret(i) = ret(i) + dot(a, G(dist(x, xi(i, :)))); endfor endif unwind_protect_cleanup warning (warn_state, "Octave:broadcast"); end_unwind_protect endif endif endfunction %!shared x,y %! x = ([1:10 10.5 11.3])'; y = sin(x); %!assert (tpaps(x,y,1,x), y, 1E-13); %! x = rand(100, 2)*2 - 1; %! y = x(:, 1) .^ 2 + x(:, 2) .^ 2; %!assert (tpaps(x,y,1,x), y, 1E-10); splines/Makefile0000644000175000017500000000544512627052101012341 0ustar nirnir## Makefile to simplify Octave Forge package maintenance tasks PACKAGE = $(shell $(SED) -n -e 's/^Name: *\(\w\+\)/\1/p' DESCRIPTION | $(TOLOWER)) VERSION = $(shell $(SED) -n -e 's/^Version: *\(\w\+\)/\1/p' DESCRIPTION | $(TOLOWER)) #DEPENDS = $(shell $(SED) -n -e 's/^Depends[^,]*, \(.*\)/\1/p' DESCRIPTION | $(SED) 's/ *([^()]*),*/ /g') RELEASE_DIR = $(PACKAGE)-$(VERSION) RELEASE_TARBALL = $(PACKAGE)-$(VERSION).tar.gz HTML_DIR = $(PACKAGE)-html HTML_TARBALL = $(PACKAGE)-html.tar.gz MD5SUM ?= md5sum MKOCTFILE ?= mkoctfile OCTAVE ?= octave SED ?= sed TAR ?= tar TOLOWER = $(SED) -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/' .PHONY: help dist html release install all check run doc clean maintainer-clean help: @echo "Targets:" @echo " dist - Create $(RELEASE_TARBALL) for release" @echo " html - Create $(HTML_TARBALL) for release" @echo " release - Create both of the above and show md5sums" @echo @echo " install - Install the package in GNU Octave" @echo " all - Build all oct files" @echo " check - Execute package tests (w/o install)" @echo " run - Run Octave with development in PATH (no install)" @echo " doc - Build Texinfo package manual" @echo @echo " clean - Remove releases, html documentation, and oct files" @echo " maintainer-clean - Additionally remove all generated files" $(RELEASE_DIR): .hg/dirstate @echo "Creating package version $(VERSION) release ..." -rm -rf $@ hg archive --exclude ".hg*" --exclude Makefile --type files $@ chmod -R a+rX,u+w,go-w $@ $(RELEASE_TARBALL): $(RELEASE_DIR) $(TAR) cf - --posix $< | gzip -9n > $@ -rm -rf $< $(HTML_DIR): install @echo "Generating HTML documentation. This may take a while ..." -rm -rf $@ $(OCTAVE) --silent \ --eval 'graphics_toolkit ("gnuplot");' \ --eval 'pkg load generate_html $(PACKAGE);' \ --eval 'generate_package_html ("$(PACKAGE)", "$@", "octave-forge");' chmod -R a+rX,u+w,go-w $@ $(HTML_TARBALL): $(HTML_DIR) $(TAR) cf - --posix $< | gzip -9n > $@ -rm -rf $< dist: $(RELEASE_TARBALL) html: $(HTML_TARBALL) release: dist html @$(MD5SUM) $(RELEASE_TARBALL) $(HTML_TARBALL) @echo "Upload @ https://sourceforge.net/p/octave/package-releases/new/" @echo "Execute: hg tag \"$(VERSION)\"" install: $(RELEASE_TARBALL) @echo "Installing package locally ..." $(OCTAVE) --silent --eval 'pkg install $(RELEASE_TARBALL);' all: check: all $(OCTAVE) --silent \ --eval 'addpath (fullfile ([pwd filesep "inst"]));' \ --eval 'runtests ("inst");' run: all $(OCTAVE) --silent --persist \ --eval 'addpath (fullfile ([pwd filesep "inst"]));' doc: clean: -rm -rf $(RELEASE_DIR) $(RELEASE_TARBALL) $(HTML_TARBALL) $(HTML_DIR) maintainer-clean: clean