Commit 15792b78 authored by Sebastian Wolf's avatar Sebastian Wolf

Merge branch 'development' of git:xerus/xerus into development

parents e10f52e7 2ecfe1da
Pipeline #1054 failed with stages
in 3 minutes and 22 seconds
......@@ -7,7 +7,8 @@ help:
@printf "Possible make targets are:\n \
\t\tshared \t\t -- Build xerus as a shared library.\n \
\t\tstatic \t\t -- Build xerus as a static library.\n \
\t\tpython \t\t -- Build the xerus python wrappers.\n \
\t\tpython2 \t\t -- Build the xerus python2 wrappers.\n \
\t\tpython3 \t\t -- Build the xerus python3 wrappers.\n \
\t\tdoc \t\t -- Build the html documentation for the xerus library.\n \
\t\tinstall \t -- Install the shared library and header files (may require root).\n \
\t\ttest \t\t -- Build and run the xerus unit tests.\n \
......@@ -142,11 +143,7 @@ warn:
# Fake rule to create arbitary headers, to prevent errors if files are moved/renamed
%.h:
ifdef BUILD_PYTHON_BINDINGS
shared: build/libxerus_misc.so build/libxerus.so build/xerus.so
else
shared: build/libxerus_misc.so build/libxerus.so
endif
build/libxerus_misc.so: $(MINIMAL_DEPS) $(MISC_SOURCES)
mkdir -p $(dir $@)
......@@ -154,14 +151,20 @@ build/libxerus_misc.so: $(MINIMAL_DEPS) $(MISC_SOURCES)
build/libxerus.so: $(MINIMAL_DEPS) $(XERUS_SOURCES) build/libxerus_misc.so
mkdir -p $(dir $@)
$(CXX) -shared -fPIC -Wl,-soname,libxerus.so $(FLAGS) -I include $(XERUS_SOURCES) -L ./build/ -Wl,--as-needed -lxerus_misc $(SUITESPARSE) $(LAPACK_LIBRARIES) $(BLAS_LIBRARIES) -o build/libxerus.so
$(CXX) -shared -fPIC -Wl,-soname,libxerus.so $(FLAGS) -I include $(XERUS_SOURCES) -L ./build/ -Wl,--as-needed -lxerus_misc $(SUITESPARSE) $(LAPACK_LIBRARIES) $(ARPACK_LIBRARIES) $(BLAS_LIBRARIES) -o build/libxerus.so
python2: build/python2/xerus.so
python3: build/python3/xerus.so
python: build/xerus.so
build/python2/xerus.so: $(MINIMAL_DEPS) $(PYTHON_SOURCES) build/libxerus.so
mkdir -p $(dir $@)
$(CXX) -shared -fPIC -Wl,-soname,xerus.so `$(PYTHON2_CONFIG) --cflags --ldflags` $(PYTHON_FLAGS) -I include $(PYTHON_SOURCES) -L ./build/ -Wl,--as-needed -lxerus $(BOOST_PYTHON2) -o $@
build/xerus.so: $(MINIMAL_DEPS) $(PYTHON_SOURCES) build/libxerus.so
build/python3/xerus.so: $(MINIMAL_DEPS) $(PYTHON_SOURCES) build/libxerus.so
mkdir -p $(dir $@)
$(CXX) -shared -fPIC -Wl,-soname,xerus.so `python2-config --cflags --ldflags` $(PYTHON_FLAGS) -I include $(PYTHON_SOURCES) -L ./build/ -Wl,--as-needed -lxerus $(BOOST_PYTHON) -o build/xerus.so
@# -fpermissive is needed because of a bug in the definition of BOOST_PYTHON_MODULE_INIT in <boost/python/module_init.h>
$(CXX) -shared -fPIC -Wl,-soname,xerus.so `$(PYTHON3_CONFIG) --cflags --ldflags` $(PYTHON_FLAGS) -fpermissive -I include $(PYTHON_SOURCES) -L ./build/ -Wl,--as-needed -lxerus $(BOOST_PYTHON3) -o $@
static: build/libxerus_misc.a build/libxerus.a
......@@ -183,13 +186,12 @@ else
endif
ifdef DESTDIR
INSTALL_LIB_PATH = $(DESTDIR)/lib/
INSTALL_HEADER_PATH = $(DESTDIR)/include/
INSTALL_PYTHON_PATH = $(DESTDIR)/lib/python/site-packages/
ifdef INSTALL_PYTHON2_PATH
install: build/python2/xerus.so
endif
ifdef INSTALL_PYTHON3_PATH
install: build/python3/xerus.so
endif
ifdef INSTALL_LIB_PATH
ifdef INSTALL_HEADER_PATH
install: shared
......@@ -200,8 +202,13 @@ install: shared
cp -r include/xerus $(INSTALL_HEADER_PATH)
cp build/libxerus_misc.so $(INSTALL_LIB_PATH)
cp build/libxerus.so $(INSTALL_LIB_PATH)
ifdef BUILD_PYTHON_BINDINGS
cp build/xerus.so $(INSTALL_PYTHON_PATH)
ifdef INSTALL_PYTHON2_PATH
@printf "Installing xerus.so to $(strip $(INSTALL_PYTHON2_PATH)).\n"
cp build/python2/xerus.so $(INSTALL_PYTHON2_PATH)
endif
ifdef INSTALL_PYTHON3_PATH
@printf "Installing xerus.so to $(strip $(INSTALL_PYTHON3_PATH)).\n"
cp build/python3/xerus.so $(INSTALL_PYTHON3_PATH)
endif
else
install:
......@@ -214,7 +221,7 @@ endif
$(TEST_NAME): $(MINIMAL_DEPS) $(UNIT_TEST_OBJECTS) $(TEST_OBJECTS) build/libxerus.a build/libxerus_misc.a
$(CXX) -D XERUS_UNITTEST $(FLAGS) $(UNIT_TEST_OBJECTS) $(TEST_OBJECTS) build/libxerus.a build/libxerus_misc.a $(SUITESPARSE) $(LAPACK_LIBRARIES) $(BLAS_LIBRARIES) $(CALLSTACK_LIBS) -o $(TEST_NAME)
$(CXX) -D XERUS_UNITTEST $(FLAGS) $(UNIT_TEST_OBJECTS) $(TEST_OBJECTS) build/libxerus.a build/libxerus_misc.a $(SUITESPARSE) $(LAPACK_LIBRARIES) $(ARPACK_LIBRARIES) $(BLAS_LIBRARIES) $(CALLSTACK_LIBS) -o $(TEST_NAME)
build/print_boost_version: src/print_boost_version.cpp
@$(CXX) -o $@ $<
......@@ -226,13 +233,19 @@ test: $(TEST_NAME)
./$(TEST_NAME) all
test_python2: # build/libxerus.so build/python2/xerus.so
@PYTHONPATH=build/python2:${PYTHONPATH} LD_LIBRARY_PATH=build:${LD_LIBRARY_PATH} $(PYTEST2) src/pyTests
test_python3: # build/libxerus.so build/python3/xerus.so
@PYTHONPATH=build/python3:${PYTHONPATH} LD_LIBRARY_PATH=build:${LD_LIBRARY_PATH} $(PYTEST3) src/pyTests
fullTest: $(TUTORIALS) $(TEST_NAME)
$(foreach x,$(TUTORIALS),./$(x)$(\n))
./$(TEST_NAME) all
.FORCE:
doc: .FORCE doc/parseDoxytags doc/findDoxytag
doc:
make -C doc doc
......@@ -245,7 +258,7 @@ clean:
benchmark: $(MINIMAL_DEPS) $(LOCAL_HEADERS) benchmark.cxx $(LIB_NAME_STATIC)
$(CXX) $(FLAGS) benchmark.cxx $(LIB_NAME_STATIC) $(SUITESPARSE) $(LAPACK_LIBRARIES) $(BLAS_LIBRARIES) $(CALLSTACK_LIBS) -lboost_filesystem -lboost_system -o Benchmark
$(CXX) $(FLAGS) benchmark.cxx $(LIB_NAME_STATIC) $(SUITESPARSE) $(LAPACK_LIBRARIES) $(ARPACK_LIBRARIES) $(BLAS_LIBRARIES) $(CALLSTACK_LIBS) -lboost_filesystem -lboost_system -o Benchmark
# Build rule for normal misc objects
build/.miscObjects/%.o: %.cpp $(MINIMAL_DEPS)
......@@ -286,7 +299,7 @@ endif
# Build and execution rules for tutorials
build/.tutorialObjects/%: %.cpp $(MINIMAL_DEPS) build/libxerus.a build/libxerus_misc.a
mkdir -p $(dir $@)
$(CXX) -I include $< build/libxerus.a build/libxerus_misc.a $(SUITESPARSE) $(LAPACK_LIBRARIES) $(BLAS_LIBRARIES) $(CALLSTACK_LIBS) $(FLAGS) -MMD -o $@
$(CXX) -I include $< build/libxerus.a build/libxerus_misc.a $(SUITESPARSE) $(LAPACK_LIBRARIES) $(ARPACK_LIBRARIES) $(BLAS_LIBRARIES) $(CALLSTACK_LIBS) $(FLAGS) -MMD -o $@
# Build rule for the preCompileHeader
......
......@@ -3,8 +3,13 @@
#=================================================================================================
# Xerus can be compiled either with G++ or the Clang++ frontend of the LLVM.
# Set the CXX variable to the one you want to use.
# If you want to use OpenMP, make sure that your compiler supports OpenMP 4.0.
CXX = g++
# CXX = clang++
PYTHON2_CONFIG = python2-config
PYTHON3_CONFIG = python3-config
PYTEST2 = pytest2
PYTEST3 = pytest3
#=================================================================================================
# C++ Version
......@@ -13,13 +18,6 @@ CXX = g++
# even C++17 in order to activated.
COMPATIBILITY = -std=c++11
#=================================================================================================
# Library Options
#=================================================================================================
# Xerus offers python bindings through boost python, which can be build in a seperate library object
# xerus.so
# BUILD_PYTHON_BINDINGS = TRUE
#=================================================================================================
# Optimization
......@@ -107,9 +105,10 @@ LOGGING += -D XERUS_LOG_INFO # Information that is not linke
#=================================================================================================
# Set the directories to install libxerus.
#INSTALL_LIB_PATH = /usr/local/lib64/ # Path where to install the libxerus.so shared library.
#INSTALL_HEADER_PATH = /usr/local/include/ # Path where to install the xerus header files.
#INSTALL_PYTHON_PATH = /usr/local/lib64/python2.7/site-packages/ # Path for the installation of the python bindings.
# INSTALL_LIB_PATH = /usr/local/lib/ # Path where to install the libxerus.so shared library.
# INSTALL_HEADER_PATH = /usr/local/include/ # Path where to install the xerus header files.
# INSTALL_PYTHON2_PATH = /usr/local/lib/python2.7/site-packages/ # Path for the installation of the python2 bindings.
# INSTALL_PYTHON3_PATH = /usr/local/lib/python3.5/site-packages/ # Path for the installation of the python3 bindings.
#=================================================================================================
......@@ -135,8 +134,13 @@ LAPACK_LIBRARIES = -llapacke -llapack # Standard Lapack +
# Uncomment or add the appropriate CXSparse library
SUITESPARSE = -lcholmod -lspqr
# (optional) Uncomment if not needed, iterative eigenvalue solver ARPACK-ng, see https://github.com/opencollab/arpack-ng
# ARPACK_LIBRARIES = -larpack
# OTHER += -DARPACK_LIBRARIES
# Uncomment or add the appropriate boost python library
BOOST_PYTHON = -lboost_python
BOOST_PYTHON2 = -lboost_python-py27
BOOST_PYTHON3 = -lboost_python-py35
# Custom include paths
# OTHER += -I /path/to/include
.PHONY: help doc clean serve
# ------------------------------------------------------------------------------------------------------
# Default rule should be the help message
# ------------------------------------------------------------------------------------------------------
......@@ -8,8 +10,7 @@ help:
\t\tserve \t\t -- Build the html documentation for the xerus library and offer it via 'jekyll serve'.\n \
\t\tclean \t\t -- Remove all documentation files.\n"
.FORCE:
doc: .FORCE parseDoxytags findDoxytag
doc: parseDoxytags findDoxytag
-mkdir html
doxygen doxygen/Doxyfile
./parseDoxytags
......@@ -20,7 +21,7 @@ clean:
-rm -f parseDoxytags findDoxytag
-rm -f xerus.tags xerus.tagfile
serve: .FORCE parseDoxytags findDoxytag
serve: parseDoxytags findDoxytag
-mkdir html
doxygen doxygen/Doxyfile
./parseDoxytags
......@@ -31,7 +32,7 @@ include ../makeIncludes/general.mk
include ../makeIncludes/warnings.mk
include ../makeIncludes/optimization.mk
FLAGS = $(strip $(WARNINGS) $(OPTIMIZE) $(OTHER))
FLAGS = $(strip $(WARNINGS) $(OPTIMIZE) $(OTHER)) -std=c++11
parseDoxytags: ../src/docHelper/parseDoxytags.cpp
$(CXX) $(FLAGS) ../src/docHelper/parseDoxytags.cpp -o parseDoxytags
......
#!/bin/bash
DIRNAME=$(dirname $0)
docker image rm -f firemarmot/xerus
docker image rm -f firemarmot
docker build -t firemarmot/xerus $DIRNAME/xerus
docker build -t firemarmot $DIRNAME
......@@ -36,6 +36,9 @@
// All the xerus headers
#include "xerus/blasLapackWrapper.h"
#ifdef ARPACK_LIBRARIES
#include "xerus/arpackWrapper.h"
#endif
#include "xerus/index.h"
#include "xerus/indexedTensorReadOnly.h"
#include "xerus/indexedTensorWritable.h"
......@@ -50,6 +53,7 @@
#include "xerus/tensorNetwork.h"
#include "xerus/contractionHeuristic.h"
#include "xerus/ttNetwork.h"
#include "xerus/htNetwork.h"
#include "xerus/ttStack.h"
#include "xerus/performanceData.h"
#include "xerus/measurments.h"
......
......@@ -37,5 +37,9 @@ namespace xerus { namespace uq {
TTTensor uq_ra_adf(const UQMeasurementSet& _measurments, const PolynomBasis _basisType, const std::vector<size_t>& _dimensions, const double _targetEps = 1e-8, const size_t _maxItr = 0);
TTTensor uq_ra_adf(const std::vector<std::vector<Tensor>>& _positions, const std::vector<Tensor>& _solutions, const std::vector<size_t>& _dimensions, const double _targetEps = 1e-8, const size_t _maxItr = 0);
TTTensor uq_ra_adf(const std::vector<std::vector<Tensor>>& _positions, const std::vector<Tensor>& _solutions, const std::vector<double>& _weights, const std::vector<size_t>& _dimensions, const double _targetEps = 1e-8, const size_t _maxItr = 0);
TTTensor uq_ra_adf_iv(TTTensor& _x, const UQMeasurementSet& _measurments, const PolynomBasis _basisType, const double _targetEps = 1e-8, const size_t _maxItr = 0);
}}
// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2018 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.
/**
* @file
* @brief Header file for the arpack wrapper functions.
*/
#pragma once
#ifdef ARPACK_LIBRARIES
#include <complex.h>
// fix for non standard-conform complex implementation
#undef I
#ifdef __has_include
#if __has_include("arpack.hpp")
#include "arpack.hpp"
#elif __has_include("arpack/arpack.hpp")
#include "arpack/arpack.hpp"
#else
#pragma error no arpack found
#endif
#else
#include "arpack/arpack.hpp"
#endif
#include "misc/standard.h"
#include <memory>
namespace xerus {
class Tensor;
/**
* @brief In this namespace the minimal wrappers for the ARPACK functions are collected.
* @details As an end user of xerus it should never be nessecary to call any of these functions, unless
* a seriously low level implementation of a critical part of an algorithm is required.
*/
namespace arpackWrapper {
///@brief: Solves Ax = lambda*x for x, this calls the Arpack Routine dsaupd
void solve_ev(double* const _x, const double* const _A, double* const _ev, const size_t _k, const size_t _n, double* const _resid, const size_t _maxiter, const double _eps, arpack::which const _ritz_option, int _info);
///@brief: Solves Ax = lambda*x for x, for the smallest _k eigenvalues
void solve_ev_smallest(double* const _x, const double* const _A, double* const _ev, const size_t _k, const size_t _n, double* const _resid, const size_t _maxiter, const double _eps, int _info);
///@brief: Solves Ax = lambda*x for x, for the biggest _k eigenvalues
void solve_ev_biggest(double* const _x, const double* const _A, double* const _ev, const size_t _k, const size_t _n, double* const _resid, const size_t _maxiter, const double _eps, int _info);
//TODO check if this can be simplified!!
///@brief: Solves Ax = lambda*x for x, this calls the Arpack Routine dsaupd
void solve_ev_dmrg_special(double* const _x, const Tensor& _l, const Tensor& _A, const Tensor& _A1, const Tensor& _r, double* const _ev, const size_t _k, const size_t _n, double* const _resid, const size_t _maxiter, const double _eps, arpack::which const _ritz_option, int _info);
///@brief: Solves Ax = lambda*x for x, for the smallest _k eigenvalues
void solve_ev_smallest_dmrg_special(double* const _x, const Tensor& _l, const Tensor& _A, const Tensor& _A1, const Tensor& _r, double* const _ev, const size_t _k, const size_t _n, double* const _resid, const size_t _maxiter, const double _eps, int _info);
}
}
#endif
......@@ -131,7 +131,8 @@ namespace xerus {
///@brief: Solves Ax = b for x
void solve(double* _x, const double* _A, size_t _m, size_t _n, const double* _b, size_t _p);
///@brief: Solves Ax = lambda*x for x, this calls the Lapack Routine DGEEV
void solve_ev(double* const _x, double* const _re, double* const _im, const double* const _A, const size_t _n);
///@brief: Solves min ||Ax - b||_2 for x
void solve_least_squares( double* const _x, const double* const _A, const size_t _m, const size_t _n, const double* const _b, const size_t _p);
......
This diff is collapsed.
// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2018 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.
/**
* @file
* @brief Header file for the HTStack class.
*/
#pragma once
#include "misc/check.h"
#include "tensorNetwork.h"
#include "indexedTensorMoveable.h"
namespace xerus {
template<bool isOperator> class HTNetwork;
namespace internal {
template<bool isOperator>
///@brief Internal class used to represent stacks of (possibly multiply) applications of HTOperators to either a HTTensor or HTOperator.
class HTStack final : public TensorNetwork {
public:
///@brief The number of external links in each node, i.e. one for HTTensors and two for HTOperators.
static constexpr const size_t N = isOperator?2:1;
const bool cannonicalization_required;
const size_t futureCorePosition;
explicit HTStack(const bool _canno, const size_t _corePos = 0);
HTStack(const HTStack& _other) = default;
HTStack( HTStack&& _other) = default;
virtual TensorNetwork* get_copy() const override;
HTStack& operator= (const HTStack& _other) = delete;
HTStack& operator= ( HTStack&& _other) = delete;
explicit operator HTNetwork<isOperator>();
virtual void operator*=(const value_t _factor) override;
virtual void operator/=(const value_t _divisor) override;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - Operator specializations - - - - - - - - - - - - - - - - - - - - - - - - - - */
virtual void specialized_evaluation(IndexedTensorWritable<TensorNetwork>&& , IndexedTensorReadOnly<TensorNetwork>&&) override;
virtual bool specialized_contraction(std::unique_ptr<IndexedTensorMoveable<TensorNetwork>>& _out, IndexedTensorReadOnly<TensorNetwork>&& _me, IndexedTensorReadOnly<TensorNetwork>&& _other) const override;
// virtual bool specialized_sum(std::unique_ptr<IndexedTensorMoveable<TensorNetwork>>& _out, IndexedTensorReadOnly<TensorNetwork>&& _me, IndexedTensorReadOnly<TensorNetwork>&& _other) const override;
static void contract_stack(IndexedTensorWritable<TensorNetwork>&& _me);
virtual value_t frob_norm() const override;
};
}
}
This diff is collapsed.
......@@ -1014,7 +1014,31 @@ namespace xerus {
* @param _extraDegree number of modes that @a _x and @a _B sharefor which the solution should be computed independently.
*/
void solve(Tensor &_X, const Tensor &_A, const Tensor &_B, size_t _extraDegree = 0);
/**
* @brief Solves the equation A*x = lambda*x for x and lambda and A symmetric. It calls the LAPACK routine DGEEV. It calculates the eigenvalue with smallest real part.
* @param _X Output Tensor for the result
* @param _A input Operator A symmetric with respect to matrification
* @return the smallest eigenvalue
*/
double get_smallest_eigenvalue(Tensor &_X, const Tensor &_A);
#ifdef ARPACK_LIBRARIES
/**
* @brief Solves the equation A*x = lambda*x for x and lambda and A symmetric. It calls the ARPACK routine dsaupd. It calculates the smallest algerbaic values.
* @param _X Output Tensor for the result, the eigenvector of the smallest eigenvalue
* @param _A input Operator A symmetric with respect to matrification
* @param _ev array holding smallest eigenvalue (ev[0]) after calculation
* @param _info if 0 algorithm is randomly initialized, if > 0 it takes _X as starting point
* @param _miter maximal number of iterations of algorithm
* @param _eps tolerance for iterative algorithm
*/
void get_smallest_eigenvalue_iterative(Tensor& _X, const Tensor& _A, double* const _ev, int _info, const size_t _miter, const double _eps);
void get_smallest_eigenvalue_iterative_dmrg_special(Tensor& _X, const Tensor& _l, const Tensor& _A, const Tensor& _A1, const Tensor& _r, double* const _ev, int _info, const size_t _miter, const double _eps);
#endif
/**
* @brief calculates the entrywise product of two Tensors
*/
......
......@@ -244,6 +244,38 @@ namespace xerus {
*/
static TTNetwork XERUS_warn_unused dirac(std::vector<size_t> _dimensions, const size_t _position);
/**
* @brief constructs a constant TTNetwork with the given dimensions and ranks.
* @param _dimensions the dimensions of the to be created TTNetwork.
* @param _ranks the ranks of the to be created TTNetwork.
* TODO wright Tests
*/
static TTNetwork XERUS_warn_unused constant(value_t constant, std::vector<size_t> _dimensions, const std::vector<size_t> &_ranks) {
const size_t numComponents = _dimensions.size()/N;
XERUS_REQUIRE(_dimensions.size()%N==0, "Illegal number of dimensions for TTOperator.");
XERUS_REQUIRE(_ranks.size()+1 == numComponents,"Non-matching amount of ranks given to TTNetwork::random.");
XERUS_REQUIRE(!misc::contains(_dimensions, size_t(0)), "Trying to construct a TTTensor with dimension 0 is not possible.");
XERUS_REQUIRE(!misc::contains(_ranks, size_t(0)), "Trying to construct random TTTensor with rank 0 is illegal.");
TTNetwork result(_dimensions.size());
const std::vector<size_t> targetRank = reduce_to_maximal_ranks(_ranks, _dimensions);
for(size_t i = 0; i < numComponents; ++i) {
const size_t leftRank = i==0 ? 1 : targetRank[i-1];
const size_t rightRank = (i==numComponents-1) ? 1 : targetRank[i];
if(isOperator) {
const auto constCmp = constant * Tensor::ones({leftRank, _dimensions[i], _dimensions[numComponents+i], rightRank});
result.set_component(i, constCmp);
} else {
const auto constCmp = constant * Tensor::ones({leftRank, _dimensions[i], rightRank});
result.set_component(i, constCmp);
}
}
//result.move_core(0);
return result;
}
/*- - - - - - - - - - - - - - - - - - - - - - - - - - Standard Operators - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
///@brief TTNetworks are default assignable.
TTNetwork& operator=(const TTNetwork& _other) = default;
......
# np.random.seed(1337)
# def build_TestNumpyInterface(seed, num, ext):
# rsg = np.random.RandomState(seed)
# mnkls = rsg.randint(1, 20, (num,4))
# def make_test_to_ndarray(mn, kl):
# def test(self):
# ls = rsg.randn(ext, *mn)
# rs = rsg.randn(ext, *kl)
# for l,r in zip(ls,rs):
# lr = np.kron(l,r)
# L,R = project(lr, mn, kl)
# diff = norm(lr - np.kron(L,R))
# self.assertLessEqual(diff, 1e-12)
# return test
# def make_test_from_ndarray(mn, kl):
# def test(self):
# ls = rsg.randn(ext, *mn)
# rs = rsg.randn(ext, *kl)
# for l,r in zip(ls,rs):
# lr = np.kron(l,r)
# L,R = project(lr, mn, kl)
# diff = norm(lr - np.kron(L,R))
# self.assertLessEqual(diff, 1e-12)
# return test
# odir = dict()
# for mnkl in mnkls:
# name = "test_random_{}x{}_{}x{}".format(*mnkl)
# test = make_test(mnkl[:2], mnkl[2:])
# odir[name] = test
# return type("TestRandomKroneckerSplitting", (unittest.TestCase,), odir)
# TestRandomKroneckerSplitting = build_TestNumpyInterface(0, 100, 4)
import unittest
from itertools import product
ranges = lambda *args: product(*[range(arg) for arg in args])
import xerus as xe
import numpy as np
class TestArithmetic(unittest.TestCase):
def setUp(self):
self.dimension = [10, 15, 20]
self.ranks = [1, 8, 4, 1]
def test_tensor_linear_combination(self):
ten_a = xe.Tensor.ones(self.dimension)
ten_b = xe.Tensor.ones(self.dimension) * 4
ten_c = ten_a + ten_b
for (i, j, k) in ranges(*self.dimension):
self.assertAlmostEqual(ten_c[i, j, k], 5)
from __future__ import division
import unittest
import itertools as _iter
import xerus as xe
import numpy as np
np.random.seed(1337)
ranges = lambda *args: _iter.product(*[range(arg) for arg in args])
class TestExtendedTT(unittest.TestCase):
def setUp(self):
self.dimension = [4, 6, 8]
self.ranks = [1, 8, 5, 1]
def test_from_function_set_component(self):
tt = xe.TTTensor(self.dimension)
arrs = []
for i in range(len(self.dimension)):
shape = [self.ranks[i], self.dimension[i], self.ranks[i+1]]
arr = np.random.randn(*shape)
x = xe.Tensor.from_function(shape, lambda x: arr[tuple(x)])
tt.set_component(i, x)
arrs.append(arr)
for i in range(len(self.dimension)):
self.assertTrue(np.all(arrs[i] == tt.get_component(i).to_ndarray()))
def test_eval_hermite(self):
from numpy.polynomial.hermite_e import hermeval
basis = xe.PolynomBasis.Hermite
# TODO: check with numpy hermite...
tt = xe.TTTensor(self.dimension)
arrs = []
for i in range(len(self.dimension)):
shape = [self.ranks[i], self.dimension[i], self.ranks[i+1]]
arr = np.random.randn(*shape)
x = xe.Tensor.from_function(shape, lambda x: arr[tuple(x)])
tt.set_component(i, x)
arrs.append(arr)
for (i, j, k) in ranges(*self.dimension):
x = xe.uq_tt_evaluate(tt, [j, k], basis)
x = x[[i]]
# loc_extt = extt([i, j, k])
# self.assertLessEqual(np.abs((loc_extt - loc_xett)/loc_extt), 1e-10)
import unittest
from itertools import product
ranges = lambda *args: product(*[range(arg) for arg in args])
import xerus as xe
import numpy as np
class TestNumpyInterface(unittest.TestCase):
def setUp(self):
self.dimension = [10, 15, 20]
self.ranks = [1, 8, 4, 1]
def test_to_ndarray(self):
ten = xe.TTTensor.random(self.dimension, self.ranks[1:-1])
for lia in range(ten.degree()):
comp_ten = ten.get_component(lia)
comp_dim = comp_ten.dimensions
comp_nd = comp_ten.to_ndarray()
for (i, j, k) in ranges(*comp_dim):
self.assertEqual(comp_ten[[i,j,k]], comp_nd[i,j,k])
def test_from_ndarray(self):
arr = np.random.randn(50,50)
ten = xe.Tensor.from_ndarray(arr)
for lia in range(arr.shape[0]):
for lib in range(arr.shape[1]):
self.assertEqual(ten[[lia, lib]], arr[lia,lib])
if __name__ == '__main__':
unittest.main()
import os, unittest
import xerus as xe
import numpy as np
from numpy.polynomial.legendre import legval
class TestReconstruction(unittest.TestCase):
def test_small_reconstruction_weighted(self):
# the function to approximate
def fnc(x, y):
return np.sin(2*np.pi*x)*(y[0] + 0.1*y[1]**2) + np.cos(2*np.pi*x)*y[1]
x_dim = 100
y_dim = 2
n_samples = 10000
n_test_samples = 100
deg = 2
basis = xe.PolynomBasis.Legendre
x = np.linspace(0, 1, x_dim)
def discretized_fnc(y):
return fnc(x, y)
path = os.path.join(os.path.dirname(__file__), "cm_samples.npz")
cm_samples = np.load(path)
nodes = cm_samples["samples"][:n_samples]
values = [xe.Tensor.from_ndarray(discretized_fnc(y)) for y in nodes]
vector = lambda x: xe.Tensor.from_ndarray(legval(x, np.eye(deg+1)))
measurements = [[vector(ni) for ni in node] for node in nodes]
weights = cm_samples["weights"][:n_samples]
dimension = [x_dim] + [deg+1]*y_dim
reco = xe.uq_ra_adf(measurements, values, weights, dimension, targeteps=1e-8, maxitr=70)
#TODO: implement a xerus function: tt_evaluate(tt, pos, pos2meas) where pos2meas is a function pos2meas(int mode, int idx, pos) that calculates the idx-th basis function in the given mode
#TODO: implement a xerus function: measurements(pos_vector, pos2meas)
test_nodes = 2*np.random.rand(n_test_samples, y_dim)-1
error = 0
for y in test_nodes:
res = xe.uq_tt_evaluate(reco, y, basis).to_ndarray()
ref = discretized_fnc(y)
error += np.linalg.norm(res - ref)**2 / np.linalg.norm(ref)**2
error = np.sqrt(error) / n_test_samples
self.assertLessEqual(error, 1e-3)
def test_small_reconstruction_explicit(self):
# the function to approximate
def fnc(x, y):
return np.sin(2*np.pi*x)*(y[0] + 0.1*y[1]**2) + np.cos(2*np.pi*x)*y[1]
x_dim = 100
y_dim = 2
n_samples = 10000
n_test_samples = 100
deg = 2
basis = xe.PolynomBasis.Legendre
x = np.linspace(0, 1, x_dim)
def discretized_fnc(y):
return fnc(x, y)
nodes = 2*np.random.rand(n_samples, y_dim)-1
values = [xe.Tensor.from_ndarray(discretized_fnc(y)) for y in nodes]
vector = lambda x: xe.Tensor.from_ndarray(legval(x, np.eye(deg+1)))
measurements = [[vector(ni) for ni in node] for node in nodes]
dimension = [x_dim] + [deg+1]*y_dim
reco = xe.uq_ra_adf(measurements, values, dimension, targeteps=1e-8, maxitr=70)
#TODO: implement a xerus function: tt_evaluate(tt, pos, pos2meas) where pos2meas is a function pos2meas(int mode, int idx, pos) that calculates the idx-th basis function in the given mode