initial commit with a working interpolation code

This commit is contained in:
David Holzmüller 2019-03-18 22:26:59 +01:00
commit cc78e036b2
12 changed files with 837 additions and 0 deletions

2
.clang-format Normal file
View File

@ -0,0 +1,2 @@
BasedOnStyle: Google
ColumnLimit: 100

36
.gitignore vendored Normal file
View File

@ -0,0 +1,36 @@
*~
*.pdf
*.synctex.gz
*.log
*.aux
*.toc
*.out
*.dvi
*.bbl
*.blg
*.nav
*.snm
*.auxlock
*.dpth
*.md5
build/*
TexCode/*
!TexCode/info.txt
measurements/*
*.hi
!references/*.pdf
.cproject
.project
.settings
Debug
Release
*.pyc
*.os
*.o
*.so
*.jar
*.pydevproject

40
CMakeLists.txt Normal file
View File

@ -0,0 +1,40 @@
cmake_minimum_required(VERSION 2.8)
project(fast_sparse_interpolation CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fmessage-length=0 -std=c++11 -D_GNU_SOURCE=1 -D_REENTRANT -Dlinux -D__linux__ -Dx86_64 -D__x86_64__")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g3 -O0")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2") #-mtune=native -march=native
set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} -L/usr/local/lib")
link_directories(/usr/local/lib)
file(GLOB SRC "src/*.cpp")
file(GLOB INC "src/*.hpp")
file(GLOB INC_TEST "test/*.hpp")
option(BUILD_TEST ON)
## Build application
add_library(fast_sparse_interpolation ${SRC})
include_directories("${PROJECT_SOURCE_DIR}/src")
if(BUILD_TEST)
if(BUILD_TEST STREQUAL "ON")
file(GLOB SRC_TEST "test/*.cpp")
add_executable(fsi-test ${SRC_TEST})
include_directories("${PROJECT_SOURCE_DIR}/src")
target_link_libraries(fast_sparse_interpolation)
endif()
endif()
install(TARGETS fast_sparse_interpolation DESTINATION lib)
install(FILES ${INC} DESTINATION include/sfcpp)

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

13
Makefile Normal file
View File

@ -0,0 +1,13 @@
all: release
#.PHONY: release
release:
mkdir -p build
cd build && cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_TEST=ON .. && make -j4 VERBOSE=1
debug:
mkdir -p build
cd build && cmake -DCMAKE_BUILD_TYPE=Debug -DBUILD_TEST=ON .. && make -j4 VERBOSE=1
install:
cd build && sudo make install

67
NOTICE Normal file
View File

@ -0,0 +1,67 @@
If you use the sfc part of this project for research purposes, please cite one of the following publications:
David Holzmüller: Efficient Neighbor-Finding on Space-Filling Curves. Bachelor Thesis (2017)
The following files contain code taken from the SG++ project:
src/files/files.cpp
src/files/files.hpp
src/time/Stopwatch.hpp
src/time/Stopwatch.cpp
========================================================================
SG++ copyright notice (BSD License):
========================================================================
The software SG++ is developed by The SG++ Project which is the
owner of the software.
According to good scientific practice, publications on results
achieved in whole or in part due to SG++ have to cite at least one
paper presenting the SG++ software.
The owner wishes to make the software available to all users to use,
reproduce, modify, distribute and redistribute also for commercial
purposes under the following conditions of the original BSD
license. Linking the SG++ module statically or dynamically with other
modules is making a combined work based on SG++. Thus, the terms and
conditions of this license cover the whole combination. As a special
exception, the copyright holders of SG++ give you permission to link
it with independent modules or to instantiate templates and macros
from SG++'s source files to produce an executable, regardless of the
license terms of these independent modules, and to copy and distribute
the resulting executable under terms of your choice, provided that you
also meet, for each linked independent module, the terms and
conditions of this license of that module.
Copyright (c) 2008-today The SG++ Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
All advertising materials mentioning features or use of this software must
display the following acknowledgement: "This product includes the software
SG++ developed 2008-today by The SG++ Project and its contributors."
Neither the name of The SG++ Project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

47
README.md Normal file
View File

@ -0,0 +1,47 @@
The sfcpp library is published under an Apache 2.0 license. The sfc part of this library is described in my bachelor thesis (https://arxiv.org/abs/1710.06384). If you use the sfc part of this project for research purposes, please cite one of the following publications:
- David Holzmüller: Efficient Neighbor-Finding on Space-Filling Curves. Bachelor Thesis (2017).
The sfcpp library can be compiled by executing the top-level Makefile (make debug / make release). This Makefile executes cmake on CMakeLists.txt to generate a Makefile in the build folder, which is then automatically executed using make to compile the library.
The modules img, sfc and the test code can be excluded from the build process. The test code requires all modules to be built and the img module requires the OpenCV libraries to be installed. The modules latex and sfc use the Color class of the img module.
The sfcpp library requires the libraries Eigen3 and boost. It has only been tested on an Ubuntu system but contains very little platform-dependent code and should be rather easy to port to other systems.
The sfcpp library contains the following modules:
cpp - currently unimplemented, contains some class stubs for C++ code generation
data - contains data structures
files - contains miscellaneous functions for file handling
geo - contains geometric functions:
- ConvexPolytope represents the face structure of a convex polytope
- QuickHullAlgorithm can compute such a polytope as the convex hull of a list of vertices
- coordinate system, point and vector classes for conversion between different coordinate systems and representation of 3D points and vectors
img - contains OpenCV wrappers for image processing
latex - contains classes for generation of LaTeX code and a submodule latex::tikz for generation of TikZ code
math - contains mathematical functions and classes representing mathematical objects
sfc - contains code for computations around space-filling curves:
- The KDCurveSpecification and CurveSpecification classes can be used to specify a curve
- The CurveInformation class computes informations about a CurveSpecification
- The CurveRenderer class can be used to generate TikZ graphics visualizing curves
- Several Algorithms classes provide optimized algorithms for different curves
- Some of the remaining classes are currently unimplemented because they were intended for code generation
strings - contains string helper functions
time - contains a Stopwatch class
A separate folder called "test" contains code that is compiled for execution and linked against the library. Currently, it contains code for rendering and analyzing space-filling curves and making performance tests. The code there can also be used as an example of how to use the sfc module.
To run the script ./prepend_header.sh, modify it to only prepend the header in files that do not contain one and run
shopt -s globstar
beforehand

16
header.txt Normal file
View File

@ -0,0 +1,16 @@
/* Copyright 2017 The sfcpp Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

11
prepend_header.sh Normal file
View File

@ -0,0 +1,11 @@
for f in **/*.hpp; do
cat ./header.txt $f > $f.new
mv $f.new $f
done
for f in **/*.cpp; do
cat ./header.txt $f > $f.new
mv $f.new $f
done

8
src/Interpolation.cpp Normal file
View File

@ -0,0 +1,8 @@
// Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#include "Interpolation.hpp"
namespace fsi {} /* namespace fsi */

325
src/Interpolation.hpp Normal file
View File

@ -0,0 +1,325 @@
// Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#pragma once
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <iostream>
#include <vector>
namespace fsi {
class BoundedSumIterator {
size_t d;
size_t bound;
std::vector<size_t> index_head; // contains all entries of the index except the last one
size_t index_head_sum;
bool is_done;
public:
BoundedSumIterator(size_t d, size_t bound)
: d(d), bound(bound), index_head(d - 1, 0), index_head_sum(0), is_done(false){};
/**
* At the current multi-index (i_1, ..., i_{d-1}, 0), return how many multi-indices starting with
* (i_1, ..., i_{d-1}) are contained in the multi-index set, then advance to the next multi-index
* that ends with a zero.
*/
size_t lastDimensionCount() { return bound - index_head_sum + 1; }
void next() {
if (bound > index_head_sum) {
index_head_sum += 1;
index_head[d - 2] += 1;
} else {
int dim = d - 2;
for (; dim >= 0 && index_head[dim] == 0; --dim) {
// reduce dimension until entry is nonzero
}
if (dim > 0) {
index_head_sum -= (index_head[dim] - 1);
index_head[dim] = 0;
index_head[dim - 1] += 1;
} else if (dim == 0) {
index_head[dim] = 0;
index_head_sum = 0;
is_done = true;
}
}
}
size_t firstIndex() { return index_head[0]; }
size_t indexAt(size_t dim) { return index_head[dim]; }
bool done() { return is_done; }
void reset() {
index_head = std::vector<size_t>(d - 1, 0);
index_head_sum = 0;
is_done = false;
}
size_t dim() { return d; }
std::vector<size_t> indexBounds() { return std::vector<size_t>(d, bound + 1); }
};
class StandardBoundedSumIterator {
size_t d;
size_t bound;
std::vector<size_t> index; // contains all entries of the index except the last one
size_t index_sum;
bool is_done;
public:
StandardBoundedSumIterator(size_t d, size_t bound)
: d(d), bound(bound), index(d, 0), index_sum(0), is_done(false){};
/**
* At the current multi-index (i_1, ..., i_{d-1}, 0), return how many multi-indices starting with
* (i_1, ..., i_{d-1}) are contained in the multi-index set, then advance to the next multi-index
* that ends with a zero.
*/
bool next() {
if (bound > index_sum) {
index_sum += 1;
index[d - 1] += 1;
} else {
int dim = d - 1;
for (; dim >= 0 && index[dim] == 0; --dim) {
// reduce dimension until entry is nonzero
}
if (dim > 0) {
index_sum -= index[dim];
index[dim] = 0;
index[dim - 1] += 1;
} else if (dim == 0) {
index[dim] = 0;
index_sum = 0;
is_done = true;
}
}
return is_done;
}
size_t firstIndex() { return index[0]; }
size_t indexSum() { return index_sum; }
bool done() { return is_done; }
void reset() {
index = std::vector<size_t>(d - 1, 0);
index_sum = 0;
is_done = false;
}
};
// class FastSparseInterpolation {
// public:
// FastSparseInterpolation(std::function<double(std::vector<double>)> const &f,
// BoundedSumIterator it, std::vector<std::function<double(size_t)>> phi);
//};
class MultiDimVector {
public:
// put the first dimension into an outer vector for processing reasons
std::vector<std::vector<double>> data;
MultiDimVector(size_t n) : data(n){};
void swap(MultiDimVector &other) { data.swap(other.data); }
void clear() {
for (size_t dim = 0; dim < data.size(); ++dim) {
data[dim].clear();
}
}
};
inline std::ostream &operator<<(std::ostream &os, boost::numeric::ublas::matrix<double> matrix) {
os << "[";
for (size_t i = 0; i < matrix.size1(); ++i) {
for (size_t j = 0; j < matrix.size2(); ++j) {
os << matrix(i, j) << " ";
}
os << "\n";
}
os << " ]";
return os;
}
template <class T>
inline std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
os << "[";
for (auto ii = v.begin(); ii != v.end(); ++ii) {
os << " " << *ii;
}
os << " ]";
return os;
}
template <typename Func, typename It, typename Phi, typename X>
MultiDimVector interpolate(Func f, It it, Phi phi, X x) {
auto n = it.indexBounds();
size_t d = it.dim();
namespace ublas = boost::numeric::ublas;
typedef ublas::matrix<double> Matrix;
std::vector<Matrix> Linv, Uinv;
// create matrices and inverted LU decompositions
for (size_t k = 0; k < d; ++k) {
// std::cout << "Matrix creation loop\n";
Matrix Mk(n[k], n[k]);
for (size_t i = 0; i < n[k]; ++i) {
for (size_t j = 0; j < n[k]; ++j) {
Mk(i, j) = phi[k](j)(x[k](i));
}
}
// std::cout << "Matrices:\n";
// std::cout << Mk << "\n";
ublas::lu_factorize(Mk);
// std::cout << Mk << "\n";
Matrix Lkinv = ublas::identity_matrix<double>(n[k]);
Matrix Ukinv = ublas::identity_matrix<double>(n[k]);
ublas::inplace_solve(Mk, Lkinv, ublas::unit_lower_tag());
ublas::inplace_solve(Mk, Ukinv, ublas::upper_tag());
// std::cout << Lkinv << "\n";
// std::cout << Ukinv << "\n";
Linv.push_back(Lkinv);
Uinv.push_back(Ukinv);
}
MultiDimVector v(n[0]);
std::cout << "Compute function values\n";
// compute function values
it.reset();
std::vector<double> point(d);
while (not it.done()) {
size_t last_dim_count = it.lastDimensionCount();
for (size_t dim = 0; dim < d - 1; ++dim) {
point[dim] = x[dim](it.indexAt(dim));
}
for (size_t last_dim_idx = 0; last_dim_idx < last_dim_count; ++last_dim_idx) {
point[d - 1] = x[d - 1](last_dim_idx);
double function_value = f(point);
v.data[it.firstIndex()].push_back(function_value);
}
it.next();
}
size_t number = 0;
for (size_t dim = 0; dim < n[0]; ++dim) {
number += v.data[dim].size();
}
std::cout << "number of points: " << number << "\n";
// for (size_t i = 0; i < v.data.size(); ++i) {
// std::cout << v.data[i] << "\n\n";
// }
std::cout << "First matrix multiplication\n";
// multiply by L^{-1}
// the multiplication is based on a cyclic permutation of the indices: the last index of v becomes
// the first index of w
for (int k = d - 1; k >= 0; --k) {
MultiDimVector w(n[k]);
auto &Lkinv = Linv[k];
it.reset();
size_t first_v_index = 0;
size_t second_v_index = 0;
while (not it.done()) {
size_t last_dim_count = it.lastDimensionCount();
for (size_t i = 0; i < last_dim_count; ++i) {
double sum = 0.0;
for (size_t j = 0; j <= i; ++j) {
// std::cout << Lkinv(i, j) << " * " << v.data[first_v_index][second_v_index + j] << "\n";
sum += Lkinv(i, j) * v.data[first_v_index][second_v_index + j];
}
w.data[i].push_back(sum);
}
second_v_index += last_dim_count;
if (second_v_index >= v.data[first_v_index].size()) {
second_v_index = 0;
first_v_index += 1;
}
it.next();
}
v.swap(w);
// for (size_t i = 0; i < v.data.size(); ++i) {
// std::cout << v.data[i] << "\n\n";
// }
}
std::cout << "Second matrix multiplication\n";
// multiply by U^{-1}
// the multiplication is based on a cyclic permutation of the indices: the last index of v becomes
// the first index of w
for (int k = d - 1; k >= 0; --k) {
MultiDimVector w(n[k]);
auto &Ukinv = Uinv[k];
it.reset();
size_t first_v_index = 0;
size_t second_v_index = 0;
while (not it.done()) {
size_t last_dim_count = it.lastDimensionCount();
for (size_t i = 0; i < last_dim_count; ++i) {
double sum = 0.0;
for (size_t j = i; j < last_dim_count; ++j) {
sum += Ukinv(i, j) * v.data[first_v_index][second_v_index + j];
}
w.data[i].push_back(sum);
}
second_v_index += last_dim_count;
if (second_v_index >= v.data[first_v_index].size()) {
second_v_index = 0;
first_v_index += 1;
}
it.next();
}
v.swap(w);
// for (size_t i = 0; i < v.data.size(); ++i) {
// std::cout << v.data[i] << "\n\n";
// }
}
return v;
}
} /* namespace fsi */

71
test/main.cpp Normal file
View File

@ -0,0 +1,71 @@
#include <Interpolation.hpp>
#include <chrono>
#include <cmath>
#include <iostream>
double f(std::vector<double> point) {
double prod = 1.0;
for (size_t dim = 0; dim < point.size(); ++dim) {
prod *= point[dim];
}
return prod;
}
class GoldenPointDistribution {
static constexpr double golden_ratio = 0.5 * (1.0 + sqrt(5));
public:
double operator()(size_t idx) {
double value = (idx + 1) * golden_ratio;
return value - int(value);
}
};
class SimplePointDistribution {
public:
double operator()(size_t idx) {
if (idx == 0) {
return 0.0;
} else if (idx == 1) {
return 1.0;
} else {
return 0.5;
}
}
};
class MonomialFunctions {
public:
std::function<double(double)> operator()(size_t idx) {
return [=](double x) { return pow(x, idx); };
}
};
template <class T>
inline std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
os << "[";
for (auto ii = v.begin(); ii != v.end(); ++ii) {
os << " " << *ii;
}
os << " ]";
return os;
}
// using namespace fsi;
int main() {
size_t d = 12;
size_t bound = 16;
fsi::BoundedSumIterator it(d, bound);
std::vector<MonomialFunctions> phi(d);
std::vector<GoldenPointDistribution> x(d);
auto start = std::chrono::high_resolution_clock::now();
auto result = fsi::interpolate(f, it, phi, x);
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time: " << elapsed.count() << " s\n";
// for (size_t i = 0; i < result.data.size(); ++i) {
// std::cout << result.data[i] << "\n\n";
// }
}