splines/ 0000775 0001750 0001750 00000000000 14425217637 010712 5 ustar nir nir splines/NEWS 0000644 0001750 0001750 00000010166 14425217567 011415 0 ustar nir nir
Summary of important user-visible changes for splines 1.3.5:
-------------------------------------------------------------------
** bug fix in csape
** syntax made compatible with Octave 8
Summary of important user-visible changes for splines 1.3.4:
-------------------------------------------------------------------
** New functions regularization, regularization2D
Summary of important user-visible changes for splines 1.3.3:
-------------------------------------------------------------------
** Demo and efficiency improvement (and accuracy fix for new fminbnd
default settings) in csaps_sel
** Bug fix in csape
Summary of important user-visible changes for splines 1.3.2:
-------------------------------------------------------------------
** bug fix in csaps
Summary of important user-visible changes for splines 1.3.1:
-------------------------------------------------------------------
** bug fix in fnplt
Summary of important user-visible changes for splines 1.3.0:
-------------------------------------------------------------------
** csape default is now Lagrange boundary conditions (Matlab compatible)
** csaps can return the fit degrees of freedom
Summary 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/CITATION 0000644 0001750 0001750 00000000316 14425217567 012047 0 ustar nir nir @software{splines,
author = {Krakauer, Nir Y. and others},
title = {Splines Package for GNU Octave},
url = {http://octave.sourceforge.net/splines},
version = {1.3.4},
date = {2021-02-23},
}
splines/COPYING 0000644 0001750 0001750 00000104513 14425217567 011751 0 ustar nir nir 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/INDEX 0000644 0001750 0001750 00000000301 14425217567 011476 0 ustar nir nir analysis >> Data analysis
Spline functions
bin_values
catmullrom
csapi
csape
csaps
csaps_sel
dedup
fnder
fnplt
fnval
regularization
regularization2D
tpaps
tps_val
tps_val_der
splines/inst/ 0000775 0001750 0001750 00000000000 14425217637 011667 5 ustar nir nir splines/inst/csaps_sel.m 0000644 0001750 0001750 00000030770 14425217567 014030 0 ustar nir nir ## Copyright (C) 2012-2018 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
##
## Herman J. Woltring (1986), A Fortran package for generalized, cross-validatory spline smoothing and differentiation, Advances in Engineering Software, 8(2):104–113
##
## @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
##minimize over pt = log(-log(p)+1) to find p with good fractional accuracy if the optimum is very small, without making TolX very small
tol_pt = 1E-6;
pt_max = log(-log(realmin)+1) + 2*tol_pt;
pt = fminbnd(@(pt) penalty_function(exp(1-exp(pt))), 0, pt_max, optimset ("TolX", tol_pt));
p = exp(1-exp(pt));
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);
%!demo
%! ni = 400; #number of evaluation points
%! n = 40; #number of given sample points
%! f = @(x) sin (2*pi*x); #function generating the synthetic data
%! x = sort (rand (n, 1)); #sampled points
%! y = f(x) + 0.1*randn (n, 1);
%! xi = linspace (0, 1, ni); #evaluation points
%! yi = csaps_sel (x,y,xi,[],'aicc');
%! plot (x, y, 's', xi, yi)
%! grid on
%! legend ('Given data', 'Spline fit')
%! title ('Spline smoothing with synthetic data sampled from sine wave with noise')
%{
#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/fnplt.m 0000644 0001750 0001750 00000003412 14425217567 013170 0 ustar nir nir ## 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.breaks),max(pp.breaks),256)';
pts = ppval(pp,xi);
if nargout == 2
x = xi;
y = pts;
elseif nargout == 1
x = [xi, pts];
else
plot(xi,pts,plt,pp.breaks,ppval(pp,pp.breaks),"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/fnder.m 0000644 0001750 0001750 00000002401 14425217567 013140 0 ustar nir nir ## 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/regularization.m 0000644 0001750 0001750 00000015050 14425217567 015105 0 ustar nir nir ## Copyright (C) 2019 Andreas Stahel
##
## 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{grid},@var{u}] =} regularization (@var{data}, @var{interval}, @var{N}, @var{F1})
## @deftypefnx {Function File} {[@var{grid},@var{u}] =} regularization (@var{data}, @var{interval}, @var{N}, @var{F1}, @var{F2})
##
## Apply a Tikhonov regularization, the functional to be minimized is@*
## @var{F} = @var{FD} + @var{lambda1}*@var{F1} + @var{lambda2}*@var{F2} @*
## = sum_(i=1)^M (y_i-u(x_i))^2
## + @var{lambda1}*int_a^b (u'(x) - @var{g1}(x))^2 dx
## + @var{lambda2}*int_a^b (u''(x) - @var{g2}(x))^2 dx
##
## With @var{lambda1} = 0 and @var{G2}(x) = 0 this leads to a smoothing spline.
##
## Parameters:
## @itemize
## @item @var{data} is a M*2 matrix with the x values in the first column and the y values in the second column.
## @item @var{interval} = [a,b] is the interval on which the regularization is applied.
## @item @var{N} is the number of subintervals of equal length. @var{grid} will consist of @var{N+1} grid points.
## @item @var{F1} is a structure containing the information on the first regularization term, integrating the square of the first derivative.
## @itemize
## @item @var{F1.lambda} is the value of the regularization parameter @var{lambda1}>=0.
## @item @var{F1.g} is the function handle for the function @var{g1(x)}. If not provided @var{G1=0} is used.
## @end itemize
## @item @var{F2} is a structure containing the information on the second regularization term, integrating the square of the second derivative. If @var{F2} is not provided @var{lambda2}=0 is assumed.
## @itemize
## @item @var{F2.lambda} is the value of the regularization parameter @var{lambda2}>=0.
## @item @var{F2.g} is the function handle for the function @var{g2(x)}. If not provided @var{G2=0} is used.
## @end itemize
## @end itemize
##
## Return values:
## @itemize
## @item @var{grid} is the grid on which @var{u} is evaluated. It consists of @var{N+1} equidistant points on the @var{interval}.
## @item @var{u} are the values of the regularized approximation to the @var{data} evaluated at @var{grid}.
## @end itemize
## @seealso{csaps, regularization2D, demo regularization}
## @end deftypefn
## Author: Andreas Stahel
## Created: 2019-03-26
function [grid,u] = regularization (data, interval, N, F1, F2)
a = interval (1); b = interval (2);
grid = linspace (a, b, N + 1)';
dx = grid (2) - grid (1);
x = data (:, 1);
## select points in interval only
ind = find ((x >= a) .* (x <= b));
x = x (ind);
y = data (:, 2); y = y (ind);
M = length (x);
Interp = sparse (M, N + 1); ## interpolation matrix
pos = floor ((x - a) / dx) + 1;
theta = mod ((x - a) / dx, 1);
for ii = 1:M
if theta (ii) > 10*eps
Interp (ii, pos (ii)) = 1 - theta (ii);
Interp (ii, pos (ii) + 1) = theta (ii);
else
Interp (ii, pos (ii)) = 1;
endif
endfor
mat = Interp' * Interp;
rhs = (Interp' * y);
if isfield (F1, 'lambda')
A1 = spdiags ([-ones(N, 1), +ones(N, 1)], [0, 1], N, N + 1) / dx;
mat = mat + F1.lambda * dx * A1' * A1;
if isfield (F1, 'g')
g1 = F1.g (grid (1:end - 1) + dx / 2);
rhs = rhs + F1.lambda * dx * A1' * g1;
endif
endif
if exist ('F2')
A2 = spdiags (ones (N, 1) * [1, -2, 1], [0, 1, 2], N - 1, N + 1) / dx^2;
mat = mat + F2.lambda * dx * A2' * A2;
if isfield (F2, 'g')
g2 = F2.g (grid (2:end - 1));
rhs = rhs + F2.lambda * dx * A2' * g2;
endif
endif
u = mat \ rhs;
endfunction
%!demo
%! N = 100; interval = [0,10];
%! x = [3.2,4,5,5.2,5.6]'; y = x;
%!
%! clear F1 F2
%! %% regularize towards slope 0.1, no smoothing
%! F1.lambda = 1e-2; F1.g = @(x)0.1*ones(size(x));
%! [grid,u1] = regularization([x,y],interval,N,F1);
%! %% regularize towards slope 0.1, with some smoothing
%! F2.lambda = 1*1e-3;
%! [grid,u2] = regularization([x,y],interval,N,F1,F2);
%!
%! figure(1)
%! plot(grid,u1,'b',grid,u2,'g',x,y,'*r')
%! xlabel('x'); ylabel('solution');
%! legend('regular1','regular2','data','location','northwest')
%!demo
%! N = 1000; interval = [0,pi];
%! x = linspace( pi/4,3*pi/4,15)'; y = sin(x)+ 0.03*randn(size(x));
%!
%! clear F1 F2
%! %% regularize by smoothing only
%! F1.lambda = 0; F2.lambda = 1e-3;
%! [grid,u1] = regularization([x,y],interval,N,F1,F2);
%! %% regularize by smoothing and aim for slope 0
%! F1.lambda = 1*1e-2;
%! [grid,u2] = regularization([x,y],interval,N,F1,F2);
%!
%! figure(1)
%! plot(grid,u1,'b',grid,u2,'g',x,y,'*r')
%! xlabel('x'); ylabel('solution');
%! legend('regular1','regular2','data','location','northwest')
%!demo
%! interval = [0,1];
%! N = 400;
%! x = rand(200,1);
%! %% generate the data on four line segments, add some noise
%! y = 2 - 2*x + (x>0.25) - 2*(x>0.5).*(x<0.65)+ 0.1*randn(length(x),1);
%! clear F1
%! %% apply regularization with three different parameters
%! F1.lambda = 1e-3; [grid,u1] = regularization([x,y],interval,N,F1);
%! F1.lambda = 1e-1; [grid,u2] = regularization([x,y],interval,N,F1);
%! F1.lambda = 3e+0; [grid,u3] = regularization([x,y],interval,N,F1);
%!
%! figure(1); plot(grid,u1,'b',grid,u2,'g',grid,u3,'m',x,y,'+r')
%! xlabel('x'); ylabel('solution')
%! legend('\lambda_1=0.001','\lambda_1=0.1','\lambda_1=3','data')
%!demo
%! %% generate a smoothing spline, see also csaps() in the package splines
%! N = 1000; interval = [0,10.3];
%! x = [0 3 4 6 10]'; y = [0 1 0 1 0]';
%! clear F2
%! F2.lambda = 1e-2;
%! %% apply regularization, the result is a smoothing spline
%! [grid,u] = regularization([x,y],interval,N,0,F2);
%!
%! figure(1);
%! plot(grid,u,'b',x,y,'*r')
%! legend('spline','data')
%! xlabel('x'); ylabel('solution')
%!test
%! data = [0,0;1,1;2,2];
%! F1.lambda = 0.0; F2.lambda = 0.1;
%! [grid,u] = regularization(data,[0,1],10,F1,F2);
%! assert(norm(grid-u),0,1e-12)
%!test
%! x = linspace(-1,1,11);
%! F1.lambda = 0.01;F2.g = @(x) 2*ones(size(x)); F2.lambda = 0.01;
%! [grid,u] = regularization([x;x.^2]',[-2,2],20,F1,F2);
%! assert(u(11),7.330959483903200e-03,1e-8)
splines/inst/tpaps.m 0000644 0001750 0001750 00000012576 14425217567 013207 0 ustar nir nir ## 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, 1E3*eps);
%! x = ((1 ./ (1:100))' - 0.5) * ([0.2 0.6]);
%! y = x(:, 1) .^ 2 + x(:, 2) .^ 2;
%!assert (tpaps(x,y,1,x), y, 1E-10);
splines/inst/fnval.m 0000644 0001750 0001750 00000000715 14425217567 013156 0 ustar nir nir ## 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/csape.m 0000644 0001750 0001750 00000034204 14425217567 013143 0 ustar nir nir ## 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.
##
## @var{x} should be @var{n} by 1, @var{y} should be @var{n} by @var{m},
## @var{valc} should be 2 by @var{m} or 2 by 1
##
## 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}
## (default; if @var{valc} is not given, the slopes matched are those
## of the cubic polynomials that interpolate the first and last four points)
## @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
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
m = size (a, 2);
if exist("valc", "var") && size(valc) == [1 2]
valc = valc';
endif
b = c = zeros (n, m);
h = diff (x);
idx = ones (columns(a),1);
if (nargin < 3 || strcmp(cond,"complete"))
# set first derivative at end points
if (nargin < 4)
valc = zeros(2, m);
n_use = min(n, 4);
for i = 1:m
valc(1, i) = polyval(polyder(polyfit(x(1:n_use), a(1:n_use, i), n_use-1)), x(1));
valc(2, i) = polyval(polyder(polyfit(x(end-n_use+1:end), a(end-n_use+1:end, i), n_use-1)), x(end));
endfor
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 = zeros (2, 1);
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,:);
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;
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"))
D = diff(a) ./ h;
A = sparse (n-1);
v = zeros (n-1, m);
for i = 2:(n-2)
A(i, i-1) = h(i-1);
A(i, i) = 2 * (h(i-1) + h(i));
A(i, i+1) = h(i);
v(i, :) = 3 * (D(i, :) - D(i-1, :));
endfor
A(1, 1) = 2 * (h(1) + h(n-1));
A(1, 2) = h(1);
A(1, n-1) += h(n-1);
v(1, :) = 3 * (D(1, :) - D(n-1, :));
A(n-1, 1) = h(n-1);
A(n-1, n-2) += h(n-2);
A(n-1, n-1) = 2 * (h(n-2) + h(n-1));
v(n-1, :) = 3 * (D(n-1, :) - D(n-2, :));
c = A \ v; #this is a cyclic tridiagonal system -- the Sherwood-Morrison formula
#could be used to solve it if \ is too slow in this case
c(n,:) = c(1,:);
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
#with only 3 points, the not-a-knot cubic spline is not unique;
#we choose the one where the cubic coefficients are zero,
#which is the interpolating quadratic polynomial
c = repmat ((a(1,:) - a(3,:)) / ((x(3) - x(1)) * (x(2) - x(3))) ...
+ (a(2,:) - a(1,:)) / ((x(2) - x(1)) * (x(2) - x(3))), [3 1]);
endif
if n == 3
d = zeros (n, m);
else
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,:));
d = diff (c) ./ (3 * h(1:n - 1, idx));
endif
b = diff (a) ./ h(1:n - 1, idx)...
- h(1:n - 1, idx) / 3 .* (c(2:n,:) + 2 * c(1:n - 1,:));
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,pp1,pp2,h,valc,xi,yi
%! 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)
%!assert (ppval(csape([1 2 4],[2, 3, 6]), 3), 13/3, 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)
%!assert (ppval(csape([1 2 4],[2, 3, 6], cond, [2 1]), 3), 215/48, 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)
%!assert (ppval(csape([1 2 3],[2, 3, 5],cond), 1.5), 2.40625, 10*eps);
%!assert (ppval(csape([1 2 4],[2, 3, 6], cond), 3), 4.375, 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)
%!assert (ppval(csape([1 2 4],[2, 3, 6], cond, [1 2]), 3), 49/12, 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 assert (ppval(csape([1 2 4],[2, 3, 6], 'not-a-knot'), 3), 13/3, 10*eps);
%!test assert (ppval(csape([1 2 4 5],[2, 3, 6, 5], 'not-a-knot'), 3), 29/6, 10*eps);
%!test assert (ppval(csape([1 2 4 5 6],[2, 3, 6, 5, 6], 'not-a-knot'), 3), 141/28, 10*eps);
%!test cond='complete';
%! h = pi/6; 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), [1 2]), 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)
%! y = cos(x); valc = -sin([x(1) x(end)]); pp1 = csape(x, y, cond, valc);
%!assert (ppval(csape(x,[y y],cond, valc),x)', ...
%! repmat(ppval(pp1, x), [1 2]), 10*eps)
%!assert (polyval(pp1.coefs(1, :), [0 h])', y(1:2), 10*eps)
%!assert (polyval(pp1.coefs(2, :), [0 h])', y(2:3), 10*eps)
%!assert (polyval([3*pp1.coefs(1, 1) 2*pp1.coefs(1, 2) pp1.coefs(1, 3)], 0), valc(1), 10*eps)
%!assert (polyval([3*pp1.coefs(2, 1) 2*pp1.coefs(2, 2) pp1.coefs(2, 3)], h), valc(2), 10*eps)
%!assert (polyval([3*pp1.coefs(1, 1) 2*pp1.coefs(1, 2) pp1.coefs(1, 3)], h), polyval([3*pp1.coefs(2, 1) 2*pp1.coefs(2, 2) pp1.coefs(2, 3)], 0), 10*eps)
%!assert (polyval([6*pp1.coefs(1, 1) 2*pp1.coefs(1, 2)], h), polyval([6*pp1.coefs(2, 1) 2*pp1.coefs(2, 2)], 0), 10*eps)
%! y = [sin(x) cos(x)]; valc = [cos([x(1); x(end)]) -sin([x(1); x(end)])]; pp2 = csape(x, y, cond, valc);
%!assert (pp2.coefs([1 3], :), pp.coefs)
%!assert (pp2.coefs([2 4], :), pp1.coefs)
# more tests of correctness for periodic boundary conditions
%!test cond='periodic';
%! x = [1 2 4 5 6]'; y = [2 3 6 5 6]'; xi = 3; yi = 129/26; pp = csape (x, y, cond);
%!assert (ppval(pp, x), y, 10*eps);
%!assert (ppval(pp, xi), yi, 10*eps);
%!assert (ppval(ppder(pp), x(1)), ppval(ppder(pp), x(end)), 10*eps);
%!assert (ppval(ppder(pp, 2), x(1)), ppval(ppder(pp, 2), x(end)), 10*eps);
%! x = [1 2 4 6]'; y = [2 3 4 2]'; xi = 3; yi = 4 + 1/64; pp = csape (x, y, cond);
%!assert (ppval(pp, x), y, 10*eps);
%!assert (ppval(pp, xi), yi, 10*eps);
%!assert (ppval(ppder(pp), x(1)), ppval(ppder(pp), x(end)), 10*eps);
%!assert (ppval(ppder(pp, 2), x(1)), ppval(ppder(pp, 2), x(end)), 10*eps);
%! x = [1 2 4 5]'; y = [2 3 6 5]'; xi = 3; yi = 5.1; pp = csape (x, y, cond);
%!assert (ppval(pp, x), y, 10*eps);
%!assert (ppval(pp, xi), yi, 10*eps);
%!assert (ppval(ppder(pp), x(1)), ppval(ppder(pp), x(end)), 10*eps);
%!assert (ppval(ppder(pp, 2), x(1)), ppval(ppder(pp, 2), x(end)), 10*eps);
%! x = [1 2 4]'; y = [2 3 2]'; xi = 3; yi = 2.5; pp = csape (x, y, cond);
%!assert (ppval(pp, x), y, 10*eps);
%!assert (ppval(pp, xi), yi, 10*eps);
%!assert (ppval(ppder(pp), x(1)), ppval(ppder(pp), x(end)), 10*eps);
%!assert (ppval(ppder(pp, 2), x(1)), ppval(ppder(pp, 2), x(end)), 10*eps);
splines/inst/csaps.m 0000644 0001750 0001750 00000020105 14425217567 013154 0 ustar nir nir ## Copyright (C) 2012-2021 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} @var{df}] =} 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 of the @var{y} values; 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
##
## @var{p} should be a scalar or empty:@*
## @table @asis
## @item @var{p}=0
## maximum smoothing: straight line
## @item @var{p}=1
## no smoothing: interpolation
## @item @var{p}<0 or empty
## an intermediate amount of smoothing is chosen @*
## and the corresponding @var{p} between 0 and 1 is returned @*
## (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.
##
## @var{df} is an estimate of the degrees of freedom used in the spline fit (2 for @var{p}=0, n for @var{p}=1)
##
##
## References: @*
## Carl de Boor (1978), A Practical Guide to Splines, Springer, Chapter XIV @*
## Grace Wahba (1983), Bayesian ``confidence intervals'' for the cross-validated smoothing spline, Journal of the Royal Statistical Society, 45B(1):133-150
##
## @end deftypefn
## @seealso{spline, splinefit, csapi, ppval, dedup, bin_values, csaps_sel}
## Author: Nir Krakauer
function [ret,p,sigma2,unc_yi,df]=csaps(x,y,p=[],xi=[],w=[])
if !(isscalar(p) || isempty(p))
error('p should be a scalar or empty')
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);
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);
## add knots to either end of spline pp-form to ensure linear extrapolation
dx_minus = eps(x(1));
dx_plus = eps(x(end));
xminus = x(1) - dx_minus;
xplus = x(end) + dx_plus;
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, :) - dx_minus*bb(1, :);
ret = mkpp (x, cat (2, dd'(:)/6, cc'(:)/2, bb'(:), aa'(:)), m);
clear a aa bb cc dd slope_minus slope_plus u #these values are no longer needed
if ~isempty (xi)
ret = ppval (ret, xi);
endif
if (isargout (4) && isempty (xi))
unc_yi = [];
endif
if isargout (3) || (isargout (4) && ~isempty (xi)) || isargout (5)
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
df = n;
return
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
df = trace (A);
sigma2 = mean (MSR(:)) * (n / (n-df)); #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,yi,p,sigma2,unc_yi,df
%! 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);
%! [yi,p,sigma2,unc_yi,df] = csaps(x,y,1,xi);
%!assert (yi, ppval(csape(x, y, "variational"), xi), eps);
%!assert (p, 1);
%!assert (unc_yi, zeros(size(xi)));
%!assert (sigma2, 0);
%!assert (df, numel(x));
%! [yi,p,~,~,df] = csaps(x,y,0,xi);
%!assert (yi, polyval(polyfit(x, y, 1), xi), 10*eps);
%!assert (p, 0);
%!assert (df, 2, 100*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/tps_val.m 0000644 0001750 0001750 00000006147 14425217567 013525 0 ustar nir nir ## 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), 100*eps);
%! x = ((1 ./ (1:100))' - 0.5) * ([0.2 0.6]);
%! 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);
%!assert (tps_val(x,c,x,true), tps_val(x,c,x,false), 100*eps);
splines/inst/regularization2D.m 0000644 0001750 0001750 00000014361 14425217567 015277 0 ustar nir nir ## Copyright (C) 2021 Andreas Stahel
##
## 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{grid},@var{u},@var{data_valid}] =} regularization2D (@var{data}, @var{box}, @var{N}, @var{lambda1},@var{lambda2})
##
## Apply a Tikhonov regularization, the functional to be minimized is@*
## @var{F} = @var{FD} + @var{lambda1} * @var{F1} + @var{lambda2} * @var{F2} @*
## = sum_(i=1)^M (y_i-u(x_i))^2 +@*
## + @var{lambda1} * dintegral (du/dx)^2+(du/dy)^2 dA +@*
## + @var{lambda2} * dintegral (d^2u/dx^2)^2+(d^2u/dy^2)^2+2*(d^2u/dxdy) dA
##
## With @var{lambda1} = 0 and @var{lambda2}>0 this leads to a thin plate smoothing spline.
##
## Parameters:
## @itemize
## @item @var{data} is a M*3 matrix with the (x,y) values in the first two columns and the y values in the third column.@*
## Only data points strictly inside the @var{box} are used
## @item @var{box} = [x0,x1;y0,y1] is the rectangle x0= 0 is the value of the first regularization parameter
## @item @var{lambda2} > 0 is the value of the secondregularization parameter
## @end itemize
##
## Return values:
## @itemize
## @item @var{grid} is the grid on which @var{u} is evaluated. It consists of
## (@var{N1+1})x(@var{N2}+1) equidistant points on the the rectangle @var{box}.
## @item @var{u} are the values of the regularized approximation to the @var{data} evaluated on the @var{grid}.
## @item @var{data_valid} returns the values data points used and the values of the regularized function at these points
## @end itemize
## @seealso {tpaps, regularization, demo regularization2D}
## @end deftypefn
## Author: Andreas Stahel
## Created: 2021-01-13
function [grid,u,data_valid] = regularization2D (data, box, N, lambda1, lambda2)
%% generate the grid
N = N+1; %%% now N is the number of grid points in either direction
x = linspace(box(1,1),box(1,2),N(1));
y = linspace(box(2,1),box(2,2),N(2));
[xx,yy] = meshgrid(x,y);
dx = diff(box(1,:))/(N(1)-1); dy = diff(box(2,:))/(N(2)-1);
grid.x = xx;
grid.y = yy;
x = data (:,1); y = data(:,2); z = data(:,3);
## select points in box only
ind = find ((x > box(1,1)) .* (x < box(1,2)) .* (y > box(2,1)) .* (y < box(2,2)));
x = x (ind); y = y (ind); z = z (ind);
%% generate the sparse interpolation matrix
M = length (x);
x_ind = floor((x-box(1,1))/dx);
%% xi = mod(x,dx)/dx;
xi = (x-box(1,1)-x_ind*dx)/dx;
y_ind = floor((y-box(2,1))/dy);
%%nu = mod(y,dy)/dy;
nu = (y-box(2,1)-y_ind*dy)/dy;
row = ones(4,1)*[1:M];
index_base = N(2)*x_ind+y_ind+1;
index = index_base + [0,N(2),1,N(2)+1]; index = index';
coeff = [(1-xi).*(1-nu),xi.*(1-nu),(1-xi).*nu,xi.*nu]; coeff = coeff';
Interp = sparse(row(:),index(:),coeff(:),M,N(1)*N(2));
mat = Interp' * Interp;
rhs = (Interp' * z);
%%% derivative with respect to x
Dx = kron(spdiags(ones(N(1),1)*[-1 1],[0 1],N(1)-1,N(1))/dx,speye(N(2)));
Wx = ones(N(2),1); Wx(1) = 1/2; Wx(N(2)) = 1/2;
Wx = kron(speye(N(1)-1),diag(Wx))*dx*dy;
%%% derivative with respect to y
Wy = ones(N(1),1); Wy(1) = 1/2; Wy(N(1)) = 1/2;
Wy = kron(diag(Wy),speye(N(2)-1))*dx*dy;
if lambda1 > 0
Dy = kron(speye(N(1)),spdiags(ones(N(2),1)*[-1 1],[0 1],N(2)-1,N(2))/dy);
mat += lambda1*(Dx'*Wx*Dx + Dy'*Wy*Dy);
endif
%%% second derivative with respect to x
Dxx = spdiags(ones(N(1),1)*[1 -1 -1 1],[-1 0 1 2],N(1)-1,N(1));
Dxx(1,1:4) = [3 -7 5 -1]; Dxx(N(1)-1,N(1)-3:N(1)) = [-1 5 -7 3];
Dxx = Dxx/(2*dx^2);
Dxx = kron(Dxx,speye(N(2)));
%%% second derivative with respect to y
Dyy = spdiags(ones(N(2),1)*[1 -1 -1 1],[-1 0 1 2],N(2)-1,N(2));
Dyy(1,1:4) = [3 -7 5 -1]; Dyy(N(2)-1,N(2)-3:N(2)) = [-1 5 -7 3];
Dyy = Dyy/(2*dy^2);
Dyy = kron(speye(N(1)),Dyy);
%%% mixed second derivative
Dy2 = kron(speye(N(1)-1),spdiags(ones(N(2),1)*[-1 1],[0 1],N(2)-1,N(2))/dy);
Dxy = Dy2*Dx*sqrt(dx*dy);
mat += lambda2*(Dxx'*Wx*Dxx + Dyy'*Wy*Dyy + 2*Dxy'*Dxy);
%%% solve
u = reshape(mat\rhs,N(2),N(1));
if nargout>2
data_valid =[x,y,Interp*u(:)];
endif
endfunction
%!demo
%! M = 100;
%! lambda1 = 0; lambda2 = 0.05;
%! x = 2*rand(M,1)-1; y = 2*rand(M,1)-1;
%! z = x.*y + 0.1*randn(M,1);
%! data = [x,y,z];
%! [grid,u] = regularization2D(data,[-1 1;-1 1],[50 50],lambda1,lambda2);
%! figure()
%! mesh(grid.x, grid.y,u)
%! xlabel('x'); ylabel('y');
%! hold on
%! plot3(data(:,1),data(:,2),data(:,3),'*b','Markersize',2)
%! hold off
%! view([30,30]);
%!demo
%! lambda1 = 0; lambda2 = 0.01;
%! M = 4; angles = [1:M]/M*2*pi;
%! data = zeros(M+1,3); data(M+1,3) = 1;
%! data(1:M,1) = cos(angles); data(1:M,2) = sin(angles);
%! [grid,u] = regularization2D(data,[-1.5 1.5;-1.5 1.5],[50 50],lambda1,lambda2);
%! figure()
%! mesh(grid.x, grid.y,u)
%! xlabel('x'); ylabel('y');
%! hold on
%! plot3(data(:,1),data(:,2),data(:,3),'*b','Markersize',2)
%! hold off
%!test
%! data = [0,0,0;1,2,3;2,0,2;0,2,2]; % data on z = x+y
%! lambda1 = 0.0 ; lambda2 = 0.1;
%! [grid,u,u_valid] = regularization2D(data,[-0.2 2.2; -0.2,2.2],[11,12],lambda1,lambda2);
%! assert(norm(data-u_valid),0,1e-12)
%! assert(norm(grid.x(:) + grid.y(:) - u(:)),0,1e-10)
%!test
%! data = [0,0,0;1,1,3;2,1,2;0,2,-2;-1.5,-1,0;-2,2,0];
%! lambda1 = 0.001 ; lambda2 = 0.01;
%! [grid,u,u_valid] = regularization2D(data,[-2.1 2.1;-2.1,2.1],[40,50],lambda1,lambda2);
%! value_at_data = [ 1.233351091378741e-01
%! 2.694454049778803e+00
%! 2.102786670571836e+00
%! -1.870655633783656e+00
%! -1.635243922246946e-02
%! -3.356775648311422e-02];
%! assert(norm(value_at_data-u_valid(:,3)),0,1e-12)
splines/inst/tps_val_der.m 0000644 0001750 0001750 00000010145 14425217567 014350 0 ustar nir nir ## 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/dedup.m 0000644 0001750 0001750 00000005311 14425217567 013146 0 ustar nir nir ## 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/catmullrom.m 0000644 0001750 0001750 00000003550 14425217567 014227 0 ustar nir nir ## 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/csapi.m 0000644 0001750 0001750 00000002151 14425217567 013143 0 ustar nir nir ## 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/bin_values.m 0000644 0001750 0001750 00000006274 14425217567 014205 0 ustar nir nir ## 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/DESCRIPTION 0000644 0001750 0001750 00000000450 14425217567 012417 0 ustar nir nir Name: splines
Version: 1.3.5
Date: 2023-05-05
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