├── .version ├── requirements-dev.txt ├── .sphinx-requirements ├── requirements.txt ├── doc ├── _static │ ├── gfx │ │ ├── logo_long.png │ │ ├── logo_short.png │ │ └── logo_favicon.png │ └── custom.css ├── architecture │ ├── classes.rst │ ├── algorithms.rst │ ├── capi.rst │ ├── calibration.rst │ ├── scipy.rst │ ├── strides.rst │ └── types.rst ├── classes │ ├── Sum.rst │ ├── Zero.rst │ ├── Blocks.rst │ ├── Diag.rst │ ├── Eye.rst │ ├── Outer.rst │ ├── Kron.rst │ ├── Sparse.rst │ ├── Fourier.rst │ ├── LowRank.rst │ ├── Matrix.rst │ ├── Partial.rst │ ├── Hadamard.rst │ ├── Parametric.rst │ ├── Polynomial.rst │ ├── Product.rst │ ├── DiagBlocks.rst │ ├── Permutation.rst │ ├── LSFRCirculant.rst │ ├── Toeplitz.rst │ ├── BlockDiag.rst │ ├── Circulant.rst │ └── Transpose.rst ├── inspection │ ├── benchmark.rst │ └── test.rst ├── algorithms │ ├── OMP.rst │ ├── ISTA.rst │ ├── FISTA.rst │ ├── STELA.rst │ └── Algorithm.rst ├── expansion │ ├── implement.rst │ └── optimize.rst ├── examples.rst ├── architecture.rst ├── examples │ ├── compressed-sensing.rst │ ├── scipy-linear-operator.rst │ ├── example_scripts │ │ └── cs_example.py │ └── compressed-sensing.py ├── algorithms.rst ├── expansion.rst ├── releases.rst ├── classes.rst ├── references.rst ├── inspection.rst ├── index.rst └── conf.py ├── .coveragerc ├── MANIFEST.in ├── fastmat ├── version.py ├── core │ ├── __init__.py │ ├── tests.pxd │ ├── types.h │ ├── strides.pxd │ ├── cmath.pxd │ ├── types.pxd │ └── resource.py ├── algorithms │ ├── __init__.py │ ├── Algorithm.pxd │ ├── OMP.pxd │ └── Algorithm.pyx ├── Eye.pxd ├── Zero.pxd ├── Sum.pxd ├── BlockDiag.pxd ├── Permutation.pxd ├── inspect │ └── __init__.py ├── Product.pxd ├── Kron.pxd ├── Partial.pxd ├── Sparse.pxd ├── Circulant.pxd ├── Diag.pxd ├── DiagBlocks.pxd ├── Polynomial.pxd ├── Hadamard.pxd ├── LowRank.pxd ├── Fourier.pxd ├── LFSRCirculant.pxd ├── Toeplitz.pxd ├── Outer.pxd ├── Blocks.pxd ├── Parametric.pxd ├── __init__.py ├── Eye.pyx ├── Zero.pyx ├── Permutation.pyx ├── DiagBlocks.pyx ├── Diag.pyx └── Sparse.pyx ├── setup.cfg ├── .gitignore ├── test ├── __init__.py └── algorithm.py ├── .github └── workflows │ ├── test-master-pr.yml │ ├── test-master.yml │ └── build-dev-pr.yml ├── pypi.md ├── CONTRIBUTING.md ├── PKG-INFO └── README.md /.version: -------------------------------------------------------------------------------- 1 | 0.2.2.post0 2 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | six 2 | cython>=0.29 3 | numpy 4 | scipy 5 | -------------------------------------------------------------------------------- /.sphinx-requirements: -------------------------------------------------------------------------------- 1 | sphinx 2 | scipy>=1.0 3 | numpydoc 4 | matplotlib -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | cython>=0.29 2 | numpy 3 | scipy=>1.0 4 | matplotlib 5 | -------------------------------------------------------------------------------- /doc/_static/gfx/logo_long.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EMS-TU-Ilmenau/fastmat/HEAD/doc/_static/gfx/logo_long.png -------------------------------------------------------------------------------- /doc/_static/gfx/logo_short.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EMS-TU-Ilmenau/fastmat/HEAD/doc/_static/gfx/logo_short.png -------------------------------------------------------------------------------- /doc/_static/gfx/logo_favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EMS-TU-Ilmenau/fastmat/HEAD/doc/_static/gfx/logo_favicon.png -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | plugins = Cython.Coverage 3 | omit = *.pxd 4 | 5 | [report] 6 | exclude_lines = cdef 7 | cpdef 8 | def 9 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | include makefile 4 | include .version 5 | recursive-include fastmat *.pyx 6 | recursive-include fastmat *.pxd 7 | recursive-include fastmat *.h 8 | recursive-exclude fastmat *.c 9 | recursive-include demo * 10 | recursive-include doc * 11 | -------------------------------------------------------------------------------- /fastmat/version.py: -------------------------------------------------------------------------------- 1 | 2 | # -*- coding: utf-8 -*- 3 | # This file carries the module's version information which will be updated 4 | # during execution of the installation script, setup.py. Distribution tarballs 5 | # contain a pre-generated copy of this file. 6 | 7 | __version__ = '0.2.2.post0' 8 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md 3 | license_files = LICENSE 4 | 5 | [bdist_wheel] 6 | universal = 1 7 | 8 | [egg_info] 9 | tag_build = 10 | tag_date = 0 11 | 12 | [build_sphinx] 13 | source-dir = doc/source/ 14 | build-dir = doc/build/ 15 | config-dir = doc/source/ 16 | -------------------------------------------------------------------------------- /doc/_static/custom.css: -------------------------------------------------------------------------------- 1 | .pixelated { 2 | image-rendering: pixelated; 3 | image-rendering: -moz-crisp-edges; 4 | } 5 | 6 | .icon { 7 | image-rendering: crisp-edges; 8 | image-rendering: -moz-crisp-edges; 9 | width: 120px; 10 | margin-right: auto; 11 | margin-left: auto; 12 | } 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # python stuff 2 | *.pyc 3 | *.pyo 4 | 5 | # prevent built pdfs to be automatically included to commits every time 6 | doc/*.pdf 7 | 8 | # docu stuff 9 | *.toc 10 | *.aux 11 | *.blg 12 | *.out 13 | *.log 14 | *.nvm 15 | *.snm 16 | doc/output/* 17 | doc/output/* 18 | 19 | # windows cython output 20 | fastmat/*.dll 21 | *.pyd 22 | 23 | # general stuff 24 | *.bak 25 | *.html 26 | 27 | # build stuff 28 | dist/* 29 | build/* 30 | fastmat.egg-info 31 | *.egginfo 32 | *.egg 33 | 34 | # testing stuff 35 | test/results* 36 | 37 | # benchmark stuff 38 | *.csv 39 | 40 | # setup stuff 41 | setup.files 42 | 43 | # cython stuff 44 | *.c 45 | *.so 46 | 47 | # coverage results 48 | .coverage 49 | 50 | # kate swap 51 | *.kate-swp 52 | -------------------------------------------------------------------------------- /fastmat/core/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | from .calibration import * 19 | from .resource import * 20 | -------------------------------------------------------------------------------- /doc/architecture/classes.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _classes: 17 | 18 | Matrix Class Model 19 | ================== 20 | -------------------------------------------------------------------------------- /doc/architecture/algorithms.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _algorithms: 17 | 18 | Algorithm Class Model 19 | ===================== 20 | -------------------------------------------------------------------------------- /doc/classes/Sum.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Sum: 17 | 18 | Matrix Sum 19 | ========== 20 | 21 | .. autoclass:: fastmat.Sum 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Zero.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Zero: 17 | 18 | Zero Matrix 19 | =========== 20 | 21 | .. autoclass:: fastmat.Zero 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2023 Sebastian Semper, Christoph Wagner 3 | # https://www.tu-ilmenau.de/it-ems/ 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | from .interface import TestInterface 17 | from .algorithm import TestAlgorithm 18 | from .classes import TestClass 19 | from fastmat.core.tests import TestCore 20 | -------------------------------------------------------------------------------- /doc/classes/Blocks.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Blocks: 17 | 18 | Block Matrix 19 | ============ 20 | 21 | .. autoclass:: fastmat.Blocks 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Diag.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Diag: 17 | 18 | Diagonal Matrix 19 | =============== 20 | 21 | .. autoclass:: fastmat.Diag 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Eye.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Eye: 17 | 18 | Identity Matrix 19 | =============== 20 | 21 | .. autoclass:: fastmat.Eye 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Outer.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Outer: 17 | 18 | Outer Product 19 | ============= 20 | 21 | .. autoclass:: fastmat.Outer 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/inspection/benchmark.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _benchmarking: 17 | 18 | Benchmarking fastmat Classes 19 | ============================ 20 | 21 | To be delivered (somewhere in time). 22 | -------------------------------------------------------------------------------- /doc/classes/Kron.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Kron: 17 | 18 | Kronecker Product 19 | ================= 20 | 21 | .. autoclass:: fastmat.Kron 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Sparse.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Sparse: 17 | 18 | Sparse Matrix 19 | ============= 20 | 21 | .. autoclass:: fastmat.Sparse 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /fastmat/core/tests.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2023 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | import numpy as np 20 | cimport numpy as np 21 | 22 | from .strides cimport * 23 | from .types cimport * 24 | 25 | cimport numpy as np 26 | -------------------------------------------------------------------------------- /doc/algorithms/OMP.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _OMP: 17 | 18 | OMP Algorithm 19 | ============= 20 | 21 | .. autoclass:: fastmat.algorithms.OMP 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Fourier.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Fourier: 17 | 18 | Fourier Matrix 19 | ============== 20 | 21 | .. autoclass:: fastmat.Fourier 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/LowRank.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _LowRank: 17 | 18 | Low Rank Matrix 19 | =============== 20 | 21 | .. autoclass:: fastmat.LowRank 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Matrix.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Matrix: 17 | 18 | Matrix Base Class 19 | ================= 20 | 21 | .. autoclass:: fastmat.Matrix 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Partial.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Partial: 17 | 18 | Partial Matrix 19 | ============== 20 | 21 | .. autoclass:: fastmat.Partial 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/algorithms/ISTA.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _ISTA: 17 | 18 | ISTA Algorithm 19 | ============== 20 | 21 | .. autoclass:: fastmat.algorithms.ISTA 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Hadamard.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Hadamard: 17 | 18 | Hadamard Matrix 19 | =============== 20 | 21 | .. autoclass:: fastmat.Hadamard 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/expansion/implement.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _implementation: 17 | 18 | Developing Your own fastmat Matrix 19 | ================================== 20 | 21 | To be delivered (somewhere in time). 22 | -------------------------------------------------------------------------------- /doc/algorithms/FISTA.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _FISTA: 17 | 18 | FISTA Algorithm 19 | =============== 20 | 21 | .. autoclass:: fastmat.algorithms.FISTA 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/algorithms/STELA.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _STELA: 17 | 18 | STELA Algorithm 19 | =============== 20 | 21 | .. autoclass:: fastmat.algorithms.STELA 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Parametric.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Parametric: 17 | 18 | Parametric Matrix 19 | ================= 20 | 21 | .. autoclass:: fastmat.Parametric 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Polynomial.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Polynomial: 17 | 18 | Matrix Polynomial 19 | ================= 20 | 21 | .. autoclass:: fastmat.Polynomial 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Product.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Product: 17 | 18 | Matrix-Matrix Product 19 | ===================== 20 | 21 | .. autoclass:: fastmat.Product 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/expansion/optimize.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _optimization: 17 | 18 | Optimizing fastmat Class Implementations 19 | ======================================== 20 | 21 | To be delivered (somewhere in time). 22 | -------------------------------------------------------------------------------- /doc/classes/DiagBlocks.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _DiagBlocks: 17 | 18 | Diagonal Block Matrix 19 | ===================== 20 | 21 | .. autoclass:: fastmat.DiagBlocks 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Permutation.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Permutation: 17 | 18 | Permutation Matrix 19 | ================== 20 | 21 | .. autoclass:: fastmat.Permutation 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/algorithms/Algorithm.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Algorithm: 17 | 18 | Algorithm Base Class 19 | ==================== 20 | 21 | .. autoclass:: fastmat.algorithms.Algorithm 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/LSFRCirculant.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _LFSRCirculant: 17 | 18 | LFSR Circulant Matrix 19 | ===================== 20 | 21 | .. autoclass:: fastmat.LFSRCirculant 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/Toeplitz.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Toeplitz: 17 | 18 | (Multilevel) Toeplitz Class 19 | =========================== 20 | 21 | .. autoclass:: fastmat.Toeplitz 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/classes/BlockDiag.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | 17 | 18 | .. _BlockDiag: 19 | 20 | 21 | Block Diagonal Matrix 22 | ===================== 23 | 24 | .. autoclass:: fastmat.BlockDiag 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | -------------------------------------------------------------------------------- /doc/classes/Circulant.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Circulant: 17 | 18 | (Multilevel) Circulant Class 19 | ============================ 20 | 21 | .. autoclass:: fastmat.Circulant 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | -------------------------------------------------------------------------------- /doc/examples.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ############ 17 | Examples 18 | ############ 19 | 20 | .. toctree:: 21 | :glob: 22 | :hidden: 23 | 24 | examples/* 25 | 26 | In this section we will put some examples on the usage of fastmat (later on). 27 | -------------------------------------------------------------------------------- /fastmat/core/types.h: -------------------------------------------------------------------------------- 1 | // -*- coding: utf-8 -*- 2 | 3 | // Copyright 2018 Sebastian Semper, Christoph Wagner 4 | // https://www.tu-ilmenau.de/it-ems/ 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | // Header file for type constant definitions 19 | 20 | // define the number of different types (including TYPE_INVALID) 21 | // as a C-style definition to get around the nasty TYPE_NUM-bug 22 | #define NUM_TYPES 9 23 | -------------------------------------------------------------------------------- /doc/architecture/capi.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _capi: 17 | 18 | Performance Interface to numpy C-API 19 | ==================================== 20 | 21 | 22 | ``fastmat.core.cmath`` 23 | ------------------------ 24 | 25 | .. automodule:: fastmat.core.cmath 26 | :members: 27 | :undoc-members: 28 | :show-inheritance: 29 | -------------------------------------------------------------------------------- /doc/architecture/calibration.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _calibration: 17 | 18 | Calibration and Runtime Optimization 19 | ==================================== 20 | 21 | ``fastmat.core.calibration`` 22 | ---------------------------- 23 | 24 | .. automodule:: fastmat.core.calibration 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | -------------------------------------------------------------------------------- /doc/architecture.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ################# 17 | Architecture 18 | ################# 19 | 20 | .. toctree:: 21 | :glob: 22 | :hidden: 23 | 24 | architecture/classes 25 | architecture/algorithms 26 | architecture/scipy 27 | architecture/types 28 | architecture/capi 29 | architecture/strides 30 | architecture/calibration 31 | -------------------------------------------------------------------------------- /fastmat/algorithms/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | r""" 19 | We provide some algorithms, which make use of the speedups provided by fastmat 20 | to allow easy production use out of the box. 21 | """ 22 | # algorithms for sparse recovery 23 | 24 | from .Algorithm import Algorithm 25 | from .ISTA import ISTA 26 | from .OMP import OMP 27 | from .FISTA import FISTA 28 | from .STELA import STELA 29 | -------------------------------------------------------------------------------- /doc/inspection/test.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _testing: 17 | 18 | Testing fastmat Classes and Unit Tests 19 | ====================================== 20 | 21 | .. _ftype: 22 | 23 | Fastmat type identifiers 24 | ------------------------ 25 | 26 | ``fastmat.inspect.test`` 27 | ------------------------ 28 | 29 | .. automodule:: fastmat.inspect.test 30 | :members: 31 | :undoc-members: 32 | :show-inheritance: 33 | -------------------------------------------------------------------------------- /doc/classes/Transpose.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _Transpose: 17 | 18 | Transposition and Related Classes 19 | ================================= 20 | 21 | .. autoclass:: fastmat.Transpose 22 | :members: 23 | :undoc-members: 24 | :show-inheritance: 25 | 26 | .. autoclass:: fastmat.Hermitian 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | .. autoclass:: fastmat.Conjugate 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | -------------------------------------------------------------------------------- /fastmat/Eye.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Eye 25 | cdef class Eye(Matrix): 26 | 27 | ############################################## class methods 28 | cpdef np.ndarray _forward(Eye, np.ndarray) 29 | cpdef np.ndarray _backward(Eye, np.ndarray) 30 | cpdef np.ndarray _reference(Eye) 31 | -------------------------------------------------------------------------------- /fastmat/Zero.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Zero 25 | cdef class Zero(Matrix): 26 | 27 | ############################################## class methods 28 | cpdef np.ndarray _forward(self, np.ndarray) 29 | cpdef np.ndarray _backward(self, np.ndarray) 30 | cpdef np.ndarray _reference(self) 31 | -------------------------------------------------------------------------------- /fastmat/algorithms/Algorithm.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | import cython 20 | import numpy as np 21 | cimport numpy as np 22 | 23 | from ..Matrix cimport Matrix 24 | 25 | ################################################## class Algorithm 26 | cdef class Algorithm(object): 27 | cpdef np.ndarray _process(self, np.ndarray) 28 | cpdef handleCallback(self, object) 29 | cpdef snapshot(self) 30 | 31 | cdef dict __dict__ 32 | 33 | cdef list _trace 34 | 35 | cdef object _cbTrace 36 | cdef object _cbResult 37 | -------------------------------------------------------------------------------- /doc/examples/compressed-sensing.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. highlight:: py 17 | 18 | .. role:: python(code) 19 | :language: py 20 | 21 | .. _example-compressed-sensing: 22 | 23 | 24 | Compressed Sensing example 25 | ========================== 26 | 27 | We set up a linear forward model using a Fourier matrix as dictionary and 28 | reconstruct the underlying sparse vector from linear projections using a matrix 29 | with elements drawn randomly from a Gaussian distribution. 30 | 31 | .. plot:: examples/compressed-sensing.py 32 | :include-source: 33 | -------------------------------------------------------------------------------- /doc/algorithms.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ################### 17 | Algorithm Index 18 | ################### 19 | 20 | .. toctree:: 21 | :glob: 22 | :hidden: 23 | 24 | algorithms/* 25 | 26 | Here we list the specialized algorithms in the package for easy referencing and access. 27 | 28 | * :py:class:`fastmat.algorithms.Algorithm` base class, the mother of all algorithms. 29 | * :py:class:`fastmat.algorithms.FISTA` 30 | * :py:class:`fastmat.algorithms.ISTA` 31 | * :py:class:`fastmat.algorithms.OMP` 32 | * :py:class:`fastmat.algorithms.STELA` 33 | -------------------------------------------------------------------------------- /.github/workflows/test-master-pr.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: test PR to master branch 5 | 6 | on: 7 | pull_request: 8 | branches: [ "master" ] 9 | 10 | jobs: 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | python-version: ["3.12"] 18 | 19 | steps: 20 | - uses: actions/checkout@v3 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v3 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Install dependencies 26 | run: | 27 | python -m pip install --upgrade pip 28 | python -m pip install six setuptools pycodestyle 29 | python -m pip install -r requirements-dev.txt; 30 | - name: Check Code Style Integrity 31 | run: | 32 | # stop the build if there are Python syntax errors or undefined names 33 | make styleCheck 34 | - name: Test using the build-in test suite 35 | run: | 36 | make test PYTHON=python 37 | -------------------------------------------------------------------------------- /fastmat/Sum.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .core.types cimport * 22 | from .Matrix cimport Matrix 23 | 24 | ################################################################################ 25 | ################################################## class Sum 26 | cdef class Sum(Matrix): 27 | 28 | ############################################## class methods 29 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 30 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 31 | 32 | cpdef np.ndarray _reference(self) 33 | -------------------------------------------------------------------------------- /fastmat/BlockDiag.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | 24 | ################################################################################ 25 | ################################################## class BlockDiag 26 | cdef class BlockDiag(Matrix): 27 | 28 | ############################################## class methods 29 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 30 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 31 | cpdef np.ndarray _reference(self) 32 | -------------------------------------------------------------------------------- /.github/workflows/test-master.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: test push to master branch 5 | 6 | on: 7 | push: 8 | branches: [ "_master" ] 9 | 10 | jobs: 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | python-version: ["2.7.18", "3.5", "3.6", "3.7", "3.8", "3.9", "3.10", "3.11, 3.12"] 18 | 19 | steps: 20 | - uses: actions/checkout@v3 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v3 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Install dependencies 26 | run: | 27 | python -m pip install --upgrade pip 28 | python -m pip install six setuptools pycodestyle 29 | python -m pip install -r requirements-dev.txt; 30 | - name: Check Code Style Integrity 31 | run: | 32 | # stop the build if there are Python syntax errors or undefined names 33 | make styleCheck 34 | - name: Test using the build-in test suite 35 | run: | 36 | make test PYTHON=python 37 | -------------------------------------------------------------------------------- /fastmat/Permutation.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Permutation 25 | cdef class Permutation(Matrix): 26 | 27 | cdef public np.ndarray _sigma 28 | cdef public np.ndarray _tau 29 | 30 | ############################################## class methods 31 | cpdef np.ndarray _forward(self, np.ndarray) 32 | cpdef np.ndarray _backward(self, np.ndarray) 33 | cpdef np.ndarray _reference(self) 34 | -------------------------------------------------------------------------------- /fastmat/inspect/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | r""" 19 | fastmat.inspect 20 | =============== 21 | 22 | .. automodule:: fastmat.inspect.benchmark 23 | :members: 24 | :undoc-members: 25 | :show-inheritance: 26 | 27 | .. automodule:: fastmat.inspect.common 28 | :members: 29 | :undoc-members: 30 | :show-inheritance: 31 | 32 | .. automodule:: fastmat.inspect.test 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | """ 38 | 39 | from .benchmark import BENCH, Benchmark 40 | from .test import TEST, Test 41 | from .common import NAME, arrTestDist, arrSparseTestDist, dynFormat, \ 42 | showContent, mergeDicts 43 | -------------------------------------------------------------------------------- /fastmat/Product.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Product 25 | cdef class Product(Matrix): 26 | 27 | ############################################## class variables 28 | cdef public object _scalar # Scalar product term 29 | 30 | ############################################## class methods 31 | cpdef np.ndarray _forward(self, np.ndarray) 32 | cpdef np.ndarray _backward(self, np.ndarray) 33 | cpdef np.ndarray _reference(self) 34 | -------------------------------------------------------------------------------- /fastmat/Kron.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | 24 | ################################################################################ 25 | ################################################## class Kron 26 | cdef class Kron(Matrix): 27 | 28 | ############################################## class variables 29 | cdef public tuple _dims # list of term dimensions 30 | 31 | ############################################## class methods 32 | cpdef np.ndarray _forward(self, np.ndarray) 33 | cpdef np.ndarray _backward(self, np.ndarray) 34 | cpdef np.ndarray _reference(self) 35 | -------------------------------------------------------------------------------- /fastmat/Partial.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Partial 25 | cdef class Partial(Matrix): 26 | 27 | ############################################## class variables 28 | cdef public np.ndarray _rowSelection # Support row indices 29 | cdef public np.ndarray _colSelection # Support col indices 30 | 31 | ############################################## class methods 32 | cpdef np.ndarray _forward(self, np.ndarray) 33 | cpdef np.ndarray _backward(self, np.ndarray) 34 | cpdef np.ndarray _reference(self) 35 | -------------------------------------------------------------------------------- /fastmat/Sparse.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Sparse 25 | cdef class Sparse(Matrix): 26 | 27 | ############################################## class variables 28 | cdef public object _spArray # Some scipy sparse matrix 29 | cdef public object _spArrayH # hermitian of _spArray 30 | 31 | ############################################## class methods 32 | cpdef np.ndarray _forward(self, np.ndarray) 33 | cpdef np.ndarray _backward(self, np.ndarray) 34 | cpdef np.ndarray _reference(self) 35 | -------------------------------------------------------------------------------- /doc/expansion.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _user-defined-classes: 17 | 18 | ######################## 19 | User Defined Classes 20 | ######################## 21 | 22 | .. toctree:: 23 | :glob: 24 | :hidden: 25 | 26 | expansion/* 27 | 28 | In this section we will show what needs to be done in order to 29 | :ref:`implement` a new fastmat class and detail on how to 30 | :ref:`test` it properly once it is implemented using the built-in 31 | class test system. Further, we show how to evaluate the performance of your 32 | implementation by using the also-built-in :ref:`benchmarking` 33 | system and give examples on how to :ref:`optimize` a given 34 | implementation to improve its performance. 35 | -------------------------------------------------------------------------------- /fastmat/Circulant.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Partial cimport Partial 22 | from .core.types cimport * 23 | 24 | ################################################################################ 25 | ################################################## class Circulant 26 | cdef class Circulant(Partial): 27 | 28 | ############################################## class variables 29 | cdef public np.ndarray _tenC # matrix diagonal-entry tensor 30 | 31 | ############################################## class methods 32 | cpdef np.ndarray _preProcSlice( 33 | self, np.ndarray, int, np.ndarray, np.ndarray) 34 | cpdef np.ndarray _genArrS(self, np.ndarray, np.ndarray) 35 | cpdef np.ndarray _reference(self) 36 | -------------------------------------------------------------------------------- /fastmat/Diag.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | 24 | ################################################################################ 25 | ################################################## class Diag 26 | cdef class Diag(Matrix): 27 | 28 | ############################################## class variables 29 | cdef public np.ndarray _vecD # matrix diagonal entry vector 30 | 31 | ############################################## class implementation methods 32 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 33 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 34 | 35 | ############################################## class testing 36 | cpdef np.ndarray _reference(self) 37 | -------------------------------------------------------------------------------- /fastmat/DiagBlocks.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | 24 | ################################################################################ 25 | ################################################## class DiagBlocks 26 | cdef class DiagBlocks(Matrix): 27 | 28 | ############################################## class variables 29 | cdef np.ndarray _tenDiags 30 | 31 | cdef intsize _numDiagsRows 32 | cdef intsize _numDiagsCols 33 | cdef intsize _numDiagsSize 34 | 35 | ############################################## class methods 36 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 37 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 38 | 39 | cpdef np.ndarray _reference(self) 40 | -------------------------------------------------------------------------------- /fastmat/Polynomial.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | 23 | ################################################################################ 24 | ################################################## class Polynomial 25 | cdef class Polynomial(Matrix): 26 | 27 | ############################################## class variables 28 | cdef public np.ndarray _coeff # Polynomial coefficients 29 | cdef public np.ndarray _coeffConj # Polynomial coefficients, 30 | # # conjugated to allow speedup 31 | 32 | ############################################## class methods 33 | cpdef np.ndarray _forward(self, np.ndarray) 34 | cpdef np.ndarray _backward(self, np.ndarray) 35 | cpdef np.ndarray _reference(self) 36 | -------------------------------------------------------------------------------- /fastmat/Hadamard.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | from .core.strides cimport STRIDE_s 24 | 25 | cdef void _hadamardCore(STRIDE_s *, STRIDE_s *, TYPE_IN) 26 | 27 | ################################################################################ 28 | ################################################## class Hadamard 29 | cdef class Hadamard(Matrix): 30 | 31 | ############################################## class variables 32 | cdef int _order # order of the hadamard matrix 33 | 34 | ############################################## class methods 35 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 36 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 37 | 38 | cpdef np.ndarray _reference(self) 39 | -------------------------------------------------------------------------------- /fastmat/LowRank.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Product cimport Product 22 | 23 | ################################################################################ 24 | ################################################## class LowRank 25 | cdef class LowRank(Product): 26 | 27 | ############################################## class variables 28 | cdef public np.ndarray _vecS # matrix singular values 29 | cdef public np.ndarray _arrU # left orthogonal matrix 30 | cdef public np.ndarray _arrV # right orthogonal matrix 31 | cdef public list _summands # list of generated rank-1 32 | # # summands 33 | 34 | ############################################## class methods 35 | cpdef np.ndarray _reference(self) 36 | -------------------------------------------------------------------------------- /fastmat/Fourier.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | cimport numpy as np 19 | 20 | from .Matrix cimport Matrix 21 | from .core.types cimport * 22 | 23 | ################################################################################ 24 | ################################################## class Fourier 25 | cdef class Fourier(Matrix): 26 | 27 | ############################################## class variables 28 | cdef intsize _order # order of the fourier matrix 29 | cdef public intsize _numL # internal size 30 | cdef public np.ndarray _preMult # 31 | cdef public np.ndarray _vecConvHat # holds other convolution 32 | # # operand in image space 33 | 34 | ############################################## class methods 35 | cpdef np.ndarray _forward(self, np.ndarray) 36 | cpdef np.ndarray _backward(self, np.ndarray) 37 | cpdef np.ndarray _reference(self) 38 | -------------------------------------------------------------------------------- /fastmat/LFSRCirculant.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | import cython 18 | cimport numpy as np 19 | 20 | from .Matrix cimport Matrix 21 | from .core.types cimport * 22 | 23 | ctypedef np.uint32_t lfsrReg_t 24 | 25 | ################################################################################ 26 | ################################################## class LfsrConv 27 | cdef class LFSRCirculant(Matrix): 28 | 29 | cdef readonly int order 30 | cdef readonly lfsrReg_t polynomial 31 | cdef readonly lfsrReg_t start 32 | cdef readonly lfsrReg_t period 33 | 34 | cdef public np.ndarray _vecC 35 | cdef public np.ndarray _states 36 | 37 | cdef np.ndarray _getStates(self) 38 | cdef np.ndarray _getVecC(self) 39 | 40 | cdef void _core(self, np.ndarray, np.ndarray, bint, bint) 41 | cdef void _roll(self, np.ndarray, intsize) 42 | 43 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 44 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 45 | -------------------------------------------------------------------------------- /doc/releases.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ################# 17 | Releases 18 | ################# 19 | 20 | .. toctree:: 21 | :glob: 22 | :hidden: 23 | 24 | Rolling Stable Branch 25 | --------------------- 26 | 27 | * Github `Link `__ 28 | 29 | Version 0.2 30 | ------------- 31 | 32 | * Download `Link `__ 33 | 34 | Version 0.1.2 35 | ------------- 36 | 37 | * Download `Link `__ 38 | 39 | Version 0.1.1 40 | ------------- 41 | 42 | * Download `Link `__ 43 | * Documentation `Link `__ 44 | 45 | Version 0.1 46 | ----------- 47 | 48 | * Download `Link `__ 49 | * Documentation `Link `__ 50 | -------------------------------------------------------------------------------- /fastmat/Toeplitz.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Partial cimport Partial 22 | 23 | ################################################################################ 24 | ################################################## class Toeplitz 25 | cdef class Toeplitz(Partial): 26 | 27 | ############################################## class variables 28 | cdef public np.ndarray _tenT # matrix diagonal-entry tensor 29 | cdef public np.ndarray _arrDimRows # Rows per level 30 | cdef public np.ndarray _arrDimCols # Columns per level 31 | 32 | ############################################## class methods 33 | cpdef np.ndarray _preProcSlice( 34 | self, np.ndarray, int, np.ndarray, np.ndarray, np.ndarray 35 | ) 36 | cpdef np.ndarray _normalizeColCore( 37 | self, np.ndarray, np.ndarray, np.ndarray 38 | ) 39 | cpdef np.ndarray _normalizeRowCore( 40 | self, np.ndarray, np.ndarray, np.ndarray 41 | ) 42 | cpdef np.ndarray _reference(self) 43 | -------------------------------------------------------------------------------- /fastmat/algorithms/OMP.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2016 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | import cython 20 | import numpy as np 21 | cimport numpy as np 22 | 23 | from ..core.types cimport * 24 | from ..Matrix cimport Matrix 25 | from .Algorithm cimport Algorithm 26 | 27 | ################################################## class Algorithm 28 | cdef class OMP(Algorithm): 29 | cdef public intsize numN 30 | cdef public intsize numM 31 | cdef public intsize numL 32 | cdef public Matrix fmatA 33 | cdef public Matrix fmatC 34 | cdef public np.ndarray arrB 35 | cdef public np.ndarray arrX 36 | cdef public np.ndarray arrXtmp 37 | cdef public np.ndarray arrResidual 38 | cdef public np.ndarray arrSupport 39 | cdef public np.ndarray matPinv 40 | cdef public np.ndarray arrA 41 | cdef public np.ndarray v2 42 | cdef public np.ndarray v2n 43 | cdef public np.ndarray v2y 44 | cdef public np.ndarray newCols 45 | cdef public np.ndarray arrC 46 | cdef public np.ndarray newIndex 47 | cdef public intsize numMaxSteps 48 | cdef public intsize numStep 49 | -------------------------------------------------------------------------------- /doc/examples/scipy-linear-operator.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | 17 | .. _example-scipy-linear-operator: 18 | 19 | Solve a System of Linear Equations with Preconditioning 20 | ======================================================= 21 | 22 | The preconditioner used for solving can also be provided as a 23 | ``LinearOperator``. 24 | 25 | .. code-block:: python 26 | 27 | import fastmat as fm 28 | import numpy as np 29 | from scipy.sparse.linalg import cgs 30 | # diagonal matrix with no zeros 31 | d = np.random.uniform(1, 20, 2 ** 10) 32 | 33 | # fastmat object 34 | H = fm.Diag(d) 35 | 36 | # use the new property to generate a scipy linear operator 37 | Hs = H.scipyLinearOperator 38 | 39 | # also generate a Preconditioning linear operator, 40 | # which in this case is the exact inverse 41 | Ms = fm.Diag(1.0 / d).scipyLinearOperator 42 | 43 | # get a baseline 44 | x = np.random.uniform(1, 20, 2 ** 10) 45 | y = np.linalg.solve(H.array, x) 46 | cgs(Hs, x, tol=1e-10) 47 | cgs(Hs, x, tol=1e-10, M=Ms) 48 | -------------------------------------------------------------------------------- /fastmat/Outer.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2018 Sebastian Semper, Christoph Wagner 3 | # https://www.tu-ilmenau.de/it-ems/ 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import cython 18 | cimport numpy as np 19 | 20 | from .Matrix cimport Matrix 21 | from .core.types cimport * 22 | 23 | ################################################################################ 24 | ################################################## class Matrix 25 | cdef class Outer(Matrix): 26 | 27 | ############################################## class variables 28 | cdef public np.ndarray _vecV # matrix vertical vector 29 | cdef public np.ndarray _vecH # matrix horizontal vector 30 | cdef public np.ndarray _vecVHerm # matrix vertical vector 31 | cdef public np.ndarray _vecHConj # matrix horizontal vector 32 | cdef public np.ndarray _vecVRav # ravelled vertical vector 33 | cdef public np.ndarray _vecHRav # ravelled horizontal vector 34 | 35 | ############################################## class methods 36 | cpdef np.ndarray _forward(self, np.ndarray) 37 | cpdef np.ndarray _backward(self, np.ndarray) 38 | 39 | cpdef np.ndarray _reference(self) 40 | -------------------------------------------------------------------------------- /pypi.md: -------------------------------------------------------------------------------- 1 | # Description 2 | Scientific computing requires handling large composed or structured matrices. 3 | Fastmat is a framework for handling large composed or structured matrices. 4 | It allows expressing and using them in a mathematically intuitive way while 5 | storing and handling them internally in an efficient way. This approach allows 6 | huge savings in computational time and memory requirements compared to using 7 | dense matrix representations. Follow the development on the [github](https://github.com/EMS-TU-Ilmenau/fastmat) project page. The documentation can be found at [readthedocs](https://fastmat.readthedocs.io/). 8 | 9 | # Dependencies 10 | - Python >= 2.7 or >=3.4 11 | - Numpy >= 1.7 12 | - Scipy >= 1.0 13 | - Cython >= 0.29 14 | - soft dependencies: 15 | - matplotlib: for demos and tools that make use of plotting functions 16 | 17 | ## Authors & Contact Information 18 | - Sebastian Semper | sebastian.semper@tu-ilmenau.de 19 | Technische Universität Ilmenau, Institute for Mathematics, EMS Group 20 | - Christoph Wagner | christoph.wagner@tu-ilmenau.de 21 | Technische Universität Ilmenau, Institute for Information Technology, EMS Group 22 | - **** 23 | 24 | # Citation / Acknowledgements 25 | If you use fastmat, or parts of it, for commercial purposes you are required 26 | to acknowledge the use of fastmat visibly to all users of your work and put a 27 | reference to the project and the EMS Group at TU Ilmenau. 28 | 29 | If you use fastmat for your scientific work you are required to mention the 30 | EMS Group at TU Ilmenau and cite the following publication affiliated with the 31 | project: 32 | > C. Wagner and S. Semper, _Fast Linear Transforms in Python_, 33 | > arXiV:1710.09578, 2017 34 | > 35 | > -- https://arxiv.org/abs/1710.09578 36 | -------------------------------------------------------------------------------- /doc/classes.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ############### 17 | Class Index 18 | ############### 19 | 20 | .. toctree:: 21 | :glob: 22 | :hidden: 23 | 24 | classes/* 25 | 26 | 27 | Here we list the classes in the package for easy referencing and access. 28 | 29 | * :py:class:`fastmat.Matrix` base class, the mother of all matrices. 30 | * :py:class:`fastmat.BlockDiag` 31 | * :py:class:`fastmat.Blocks` 32 | * :py:class:`fastmat.Circulant` 33 | * :py:class:`fastmat.Conjugate` 34 | * :py:class:`fastmat.Diag` 35 | * :py:class:`fastmat.DiagBlocks` 36 | * :py:class:`fastmat.Eye` 37 | * :py:class:`fastmat.Fourier` 38 | * :py:class:`fastmat.Hadamard` 39 | * :py:class:`fastmat.Hermitian` 40 | * :py:class:`fastmat.Kron` 41 | * :py:class:`fastmat.LFSRCirculant` 42 | * :py:class:`fastmat.LowRank` 43 | * :py:class:`fastmat.Outer` 44 | * :py:class:`fastmat.Parametric` 45 | * :py:class:`fastmat.Partial` 46 | * :py:class:`fastmat.Permutation` 47 | * :py:class:`fastmat.Polynomial` 48 | * :py:class:`fastmat.Product` 49 | * :py:class:`fastmat.Sparse` 50 | * :py:class:`fastmat.Sum` 51 | * :py:class:`fastmat.Toeplitz` 52 | * :py:class:`fastmat.Transpose` 53 | * :py:class:`fastmat.Zero` 54 | -------------------------------------------------------------------------------- /fastmat/Blocks.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | 24 | ################################################################################ 25 | ################################################## class Blocks 26 | cdef class Blocks(Matrix): 27 | 28 | ############################################## class variables 29 | cdef public tuple _rows # list of list of Matrix terms 30 | # # (array of matrix terms) 31 | cdef public tuple _cols # same as _rows, transposed 32 | cdef public tuple _rowSize # heights of rows 33 | cdef public tuple _colSize # widths of columns 34 | cdef public intsize _numRows # Row-count of term array 35 | cdef public intsize _numCols # Column-count of term array 36 | 37 | ############################################## class methods 38 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 39 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 40 | 41 | cpdef np.ndarray _reference(self) 42 | -------------------------------------------------------------------------------- /doc/references.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ################# 17 | References 18 | ################# 19 | 20 | .. _ref1: 21 | .. [1] Stefan van der Walt, S. Chris Colbert and Gael 22 | Varoquaux, "The NumPy Array: A Structure for Efficient 23 | Numerical Computations", Computing in Science and 24 | Engineering, Volume 13, 2011. 25 | 26 | .. _ref2: 27 | .. [2] Rao K. Yarlagadda, John E. Hershey', "Hadamard Matrix Analysis 28 | and Synthesis, With Applications to Communications 29 | and Signal/Image Processing", The Springer International 30 | Series in Engineering and Computer Science, Volume 383, 1997 31 | 32 | .. _ref3: 33 | .. [3] Stefan Behnel, Robert Bradshaw, Craig Citro, Lisandro Dalcin, 34 | Dag Sverre Seljebotn and Kurt Smith, "Cython: The Best of Both 35 | Worlds", Computing in Science and Engineering, Volume 13,2011 36 | 37 | .. _ref4: 38 | .. [4] Fernandes, Paulo and Plateau, Brigitte and Stewart, William J., 39 | "Efficient Descriptor-Vector Multiplications in Stochastic 40 | Automata Networks", Journal of the ACM, New York, 41 | Volume 45, 1998 42 | 43 | .. _ref5: 44 | .. [5] Simon W. Golomb, "Shift Register Sequences", Holden-Day, 45 | Inc. 1967 46 | 47 | 48 | [1]_ [2]_ [3]_ [4]_ [5]_ 49 | -------------------------------------------------------------------------------- /doc/architecture/scipy.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _scipy: 17 | 18 | SciPy Interface 19 | =============== 20 | 21 | Motivation 22 | ---------- 23 | 24 | SciPy offers a large zoo of algorithms which exploit the possibility to pass a 25 | so called LinearOperator, which only provides methods for forward and backward 26 | transforms together with some simple properties like a datatype and shape 27 | parameters. This is exactly what we can provide for a specific instance of a 28 | fastmat Matrix. To this end, each fastmat Matrix has the (read only) property 29 | scipyLinearOperator, which provides a SciPy Linear operator realizing the 30 | transform specified by the fastmat object. 31 | 32 | This allows to combine fastmat and SciPy in the most efficient manner possible. 33 | Here, fastmat provides the simple and efficient description of a huge variety 34 | of linear operators, which can then be used neatly and trouble free in SciPy. 35 | 36 | Usage 37 | ----- 38 | 39 | The interface is provided by the factory 40 | :py:meth:`fastmat.Matrix.scipyLinearOperator`, which returns an instance of 41 | :py:class:`scipy.sparse.linalg.LinearOperator`. All fastmat matrices can be 42 | used from `scipy` methods supporting this interface, offering a wide range of 43 | functionality -- by combining both worlds -- to the user. 44 | 45 | For a code example, see :ref:`example-scipy-linear-operator`. 46 | -------------------------------------------------------------------------------- /fastmat/core/strides.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | import numpy as np 20 | cimport numpy as np 21 | 22 | from .types cimport * 23 | 24 | cimport numpy as np 25 | 26 | ################################################## Stride object 27 | ctypedef struct STRIDE_s: 28 | char * base 29 | intsize strideElement 30 | intsize strideVector 31 | intsize numElements 32 | intsize numVectors 33 | np.uint8_t sizeItem 34 | ftype dtype 35 | 36 | ################################################## Basic stride operations 37 | cdef void strideInit(STRIDE_s *, np.ndarray, np.uint8_t) except * 38 | cdef void strideCopy(STRIDE_s *, STRIDE_s *) 39 | cdef void strideSliceVectors(STRIDE_s *, intsize, intsize, intsize) 40 | cdef void strideSliceElements(STRIDE_s *, intsize, intsize, intsize) 41 | cdef void strideSubgrid(STRIDE_s *, 42 | intsize, intsize, intsize, intsize, intsize, intsize) 43 | cdef void strideFlipVectors(STRIDE_s *) 44 | cdef void strideFlipElements(STRIDE_s *) 45 | 46 | cdef void stridePrint(STRIDE_s *, text=?) except * 47 | 48 | 49 | ################################################## Operations with strides 50 | cdef void opCopyVector(STRIDE_s *, intsize, STRIDE_s *, intsize) except * 51 | cdef void opZeroVector(STRIDE_s *, intsize) 52 | cdef void opZeroVectors(STRIDE_s *) 53 | -------------------------------------------------------------------------------- /fastmat/Parametric.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | 24 | ctypedef object(*function)(object, object) 25 | 26 | ################################################################################ 27 | ################################################## class Hadamard 28 | cdef class Parametric(Matrix): 29 | 30 | ############################################## class variables 31 | cdef public np.ndarray _vecX # support vector of X-dimension 32 | cdef public np.ndarray _vecY # support vector of Y-dimension 33 | cdef public object _fun # Parameterizing function 34 | 35 | cdef object _funDtype # element function data type 36 | cdef bint _rangeAccess # if True, _fun will be called 37 | # # for every element separately 38 | # # (no range access calls) 39 | 40 | ############################################## class methods 41 | cdef void _core(self, np.ndarray, np.ndarray, ftype, ftype, ftype, bint) 42 | 43 | cpdef _forwardC(self, np.ndarray, np.ndarray, ftype, ftype) 44 | cpdef _backwardC(self, np.ndarray, np.ndarray, ftype, ftype) 45 | 46 | cpdef np.ndarray _reference(self) 47 | -------------------------------------------------------------------------------- /doc/inspection.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | ############################ 17 | Testing and Benchmarking 18 | ############################ 19 | 20 | .. toctree:: 21 | :glob: 22 | :hidden: 23 | 24 | inspection/* 25 | 26 | In this section we will show two built-in systems that allow you to 27 | :ref:`test` and :ref:`benchmarking` any fastmat Matrix 28 | implementation. Testing is important to verify that a certain implementation 29 | actually does what you'd expect of it and is virtually *the* essential 30 | cornerstone to writing your own user defined matrix class implementation. 31 | 32 | The scope of the implemented testing system expands to these areas 33 | (not complete): 34 | 35 | * Testing of mathematical correctness 36 | * Testing of computational accuracy 37 | * Testing of various data types (and combinations thereof) 38 | * Testing of parameter combinations 39 | * Testing for different platforms ans versions (mostly done by our CI setup) 40 | 41 | Benchmarking, however, is a valuable goodie to have in your toolbox to evaluate 42 | the performance of your implementation and to find culprits that impact the 43 | runtime or memory consumption of your implementation. Make sure to also tune in 44 | to out :ref:`optimization` section, where we detail on how to use 45 | the information gained from benchmarking your classes productively to improve 46 | your implementation. 47 | -------------------------------------------------------------------------------- /doc/architecture/strides.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _strides: 17 | 18 | Low-Overhead Array Striding Interface 19 | ===================================== 20 | 21 | Fastmat offers a special C-level interface allowing the creation, processing 22 | and manipulation of views into the underlying data of :py:class:`numpy.ndarray` 23 | objects without the overhead of creating view or memoryview objects of that 24 | array object. As the implementation is based on C structures, no interaction 25 | with the python object interface is necessary, thus increasing the efficiency 26 | of advanced linear operators from within cython code. By mimimizing memory 27 | operations occuring during view creation, structure- or object allocation or 28 | copying, this helps minimizing the already low overhead on using cython 29 | memoryviews further. 30 | 31 | 32 | The main container for defining and using strides is the ``STRIDE_s`` structure: 33 | 34 | .. code-block:: cython 35 | 36 | ctypedef struct STRIDE_s: 37 | char * base 38 | intsize strideElement 39 | intsize strideVector 40 | intsize numElements 41 | intsize numVectors 42 | np.uint8_t sizeItem 43 | ftype dtype 44 | 45 | :ref:`fastmat Type Identifier` 46 | 47 | The striding interface supports: 48 | * Two-dimensional :py:class:`numpy.ndarray` objects 49 | * Non-contiguous (striding) access into the data 50 | * Modifying views (substriding 51 | 52 | ``fastmat.core.strides`` 53 | ------------------------ 54 | 55 | .. automodule:: fastmat.core.strides 56 | :members: 57 | :undoc-members: 58 | :show-inheritance: 59 | -------------------------------------------------------------------------------- /fastmat/core/cmath.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | import numpy as np 20 | cimport numpy as np 21 | 22 | from .types cimport * 23 | 24 | cimport numpy as np 25 | 26 | ################################################## math routines 27 | 28 | ctypedef enum OP_MODE: 29 | MODE_MUL 30 | MODE_DOTROW 31 | 32 | ################################################## complexity estimation 33 | cdef int _findFFTFactors(int, int, int, int) 34 | cpdef intsize _findOptimalFFTSize(intsize, int) 35 | cpdef float _getFFTComplexity(intsize) 36 | 37 | ################################################## Array generation routines 38 | cpdef np.ndarray _arrZero(int, intsize, intsize, ntype, bint fortranStyle=?) 39 | cpdef np.ndarray _arrEmpty(int, intsize, intsize, ntype, bint fortranStyle=?) 40 | 41 | cpdef np.ndarray _arrSqueeze(object) 42 | cpdef np.ndarray _arrSqueeze1D(object data, int flags) 43 | cpdef np.ndarray _arrSqueezedCopy(object) 44 | cpdef np.ndarray _arrReshape(np.ndarray, int, intsize, intsize, np.NPY_ORDER) 45 | cpdef bint _arrResize(np.ndarray, int, intsize, intsize, np.NPY_ORDER) 46 | 47 | ################################################## Array formatting 48 | cpdef np.ndarray _arrCopyExt(np.ndarray, ntype, int) 49 | cpdef np.ndarray _arrForceType(np.ndarray, ntype) 50 | cpdef np.ndarray _arrForceAlignment(np.ndarray, int, bint fortranStyle=?) 51 | cpdef np.ndarray _arrForceTypeAlignment(np.ndarray, ntype, int, 52 | bint fortranStyle=?) 53 | 54 | cpdef bint _conjugateInplace(np.ndarray) 55 | cpdef np.ndarray _conjugate(np.ndarray) 56 | cpdef _multiply(np.ndarray, np.ndarray, np.ndarray, ftype, ftype, ftype) 57 | cpdef _dotSingleRow(np.ndarray, np.ndarray, np.ndarray, 58 | ftype, ftype, ftype, intsize) 59 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | You are welcome to participate in this project and contribute new features, bug fixes or enhancements as you see fit. 4 | 5 | ## Issues 6 | We love issues! Especially those that do not exist. But if you have found one in the sense that you think there is a bug, a feature missing or something wrong with something else, we invite you to open them plentyfully and explain what is wrong, slow or disturbing in any way. 7 | 8 | ## How this repository is organized 9 | The master branch is protected and cannot be pushed or merged into directly. Therefore you will need to do your work on a dedicated branch and issue a pull request into master when finished. There are automatic checks in place that check every merge request for code styles and errors within the classes. 10 | 11 | We aim at a subset of the [PEP8](https://www.python.org/dev/peps/pep-0008/) style guide, where we have removed the checks for E26, E116, E203, E221, E222, E225, E227, E241, E402, E731 and W504. 12 | 13 | Any commit in master will start a process of thorough testing through our CI. First, automated builds and tests will be started for Python 2, Python3 and Python3 on OS X. Then, deeper code analysis is triggered (coveralls, codacy, ...) and the results get published by these tools. Finally, if no errors were found and everything *just works*, `master` will be merged automatically into `stable`. This way we do know that `stable` is always up-to-date and working. 14 | 15 | The release of fastmat versions *into the wild* is triggered by defining a fresh version tag into the file `.version`. This then gets processed by setup.py and controls the fastmat version number used for deployment and documentation. Pypi assists us by only accepting the first build of a version. Therefore only when we update the `.version`file, a new version gets released. If and only if all wheels were built the tag specifying the release version is set for the newest commit in the `stable` branch (being the released state). 16 | 17 | ## Pull Requests 18 | We would like to organize our work by tracking ongoing work in pull requests. So as soon as you have started hacking away in a new branch, you can push it upstream and issue a pull request to get the discussion with everyone else going. If it is a larger feature or a more involved refactoring, there might be some discussion happening and we might need some iterations and modifications in your branch until we see it fit for merging. 19 | 20 | Since we aim at providing some simple checks of your code whenever pushing to some feature branch, the code itself should already be of high(ish) quality if these checks pass in the sense of coding style and test approval. 21 | 22 | Feel free to open any issues and associate them to your pull request in order to allow a more elaborate and detailed discussion of things there and also to keep everything organized and transparent. 23 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2018 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. toctree:: 17 | :maxdepth: -1 18 | :hidden: 19 | 20 | classes 21 | algorithms 22 | architecture 23 | expansion 24 | inspection 25 | examples 26 | references 27 | releases 28 | 29 | 30 | .. image:: _static/gfx/logo_long.png 31 | :width: 300px 32 | :alt: fastmat 33 | :align: center 34 | :class: pixelated 35 | 36 | --------- 37 | 38 | Introduction 39 | ------------ 40 | 41 | .. automodule:: fastmat 42 | 43 | 44 | Publications 45 | ------------ 46 | 47 | Since we created a package for scientific computing, it makes sense to use it for science. Below we list all publications, which make use of our package with varying degree. If made use of fastmat in your publication, we are happy to reference it here: 48 | 49 | - The White Paper: `Fast Linear Transforms in Python `_ 50 | - `Defect Detection from 3D Ultrasonic Measurements Using Matrix-free Sparse Recovery Algorithms `_ 51 | - `GPU-accelerated Matrix-Free 3D Ultrasound Reconstruction for Nondestructive Testing `_ 52 | 53 | If you use fastmat in your own work we kindly ask you to cite the above mentioned white paper as an acknowledgement. 54 | 55 | Public Appearances 56 | ------------------ 57 | 58 | Sometimes we also get out in the wild and present the package. The talks we held can be found below. 59 | 60 | - EuroScipy 2017 Erlangen: `PDF `_, `Youtube `_ 61 | 62 | 63 | Contributions 64 | ------------- 65 | 66 | There are many ways you as an individual can contribute. We are happy about feature requests, bug reports and of course contributions in form of additional features. To these ends, please step by at `Github `_ where we organize the work on the package. 67 | 68 | 69 | Affiliations and Credits 70 | ------------------------ 71 | 72 | Currently the project is jointly maintained by Sebastian Semper and Christoph Wagner at the `EMS group `_ at `TU Ilmenau `_. 73 | -------------------------------------------------------------------------------- /doc/examples/example_scripts/cs_example.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | import fastmat as fm 5 | import fastmat.algorithms as fma 6 | 7 | # Problem dimensions 8 | compression_factor = 5 9 | N = 256 # Problem size 10 | 11 | # Number of observations (specified over compression factor) 12 | M = int(N / compression_factor) 13 | k = 3 # sparsity level 14 | noise_power_db = -3 15 | 16 | # Ground truth of scenario 17 | ground_truth = np.zeros((N,)) 18 | ground_truth[np.random.choice(N, k, replace=False)] = np.random.randn(k) 19 | 20 | 21 | # Set up the linear signal model and reconstruction method, 22 | # consisting of Measurement Matrix `Phi` and Signal Base `Dict` 23 | Phi = fm.Matrix(np.random.randn(M, N)) 24 | Dict = fm.Hadamard(8) 25 | 26 | A = Phi * Dict 27 | alg_omp = fma.OMP(A) 28 | alg_fista = fma.FISTA(A) 29 | alg_stela = fma.STELA(A) 30 | 31 | # Now determine the actual (real-world) signal and its observation 32 | # according to the specified Measurement matrix and plot the signals 33 | # also allow for noise 34 | x_clean = Dict * ground_truth 35 | x = x_clean + 10 ** (noise_power_db / 10.0) * np.sqrt(1 / N) * ( 36 | np.linalg.norm(ground_truth) * np.random.randn(*ground_truth.shape) 37 | ) 38 | b = Phi * x 39 | 40 | # Now reconstruct the original ground truth using 41 | # * Orthogonal Matching Pursuit (OMP) 42 | # * Fast Iterative Shrinkage Thresholding Algorithm (FISTA) 43 | # * Soft-Thresholding with simplified Exact Line search Algorithm (STELA) 44 | numLambda = 1.8 45 | numSteps = 600 46 | y_omp = alg_omp.process(b, numMaxSteps=k) 47 | y_fista = alg_fista.process(b, numMaxSteps=numSteps, numLambda=numLambda) 48 | y_stela = alg_stela.process(b, numMaxSteps=numSteps, numLambda=numLambda) 49 | 50 | # Setup a simple phase transition diagram for OMP: 51 | trials = 50 52 | M_phase_transition = np.arange(k, N) 53 | true_defect_positions = np.argsort(np.abs(ground_truth), axis=0)[-k:][ 54 | :, np.newaxis 55 | ] 56 | success_rate = np.zeros(len(M_phase_transition)) 57 | for index, m_phase_transition in enumerate(M_phase_transition): 58 | for _ in range(trials): 59 | Phi_pt = fm.Matrix(np.random.randn(m_phase_transition, N)) 60 | alg_omp = fma.OMP(Phi_pt * Dict) 61 | b = Phi_pt * x 62 | recovered_support = np.argsort( 63 | np.abs(alg_omp.process(b, numMaxSteps=k)), axis=0 64 | )[-k:] 65 | if np.all(recovered_support == true_defect_positions): 66 | success_rate[index] += 1 67 | 68 | success_rate = success_rate / trials 69 | 70 | # Plot all results 71 | plt.figure(1) 72 | plt.clf() 73 | plt.title("Ground Truth") 74 | plt.plot(ground_truth) 75 | 76 | plt.figure(2) 77 | plt.clf() 78 | plt.title("Actual Signal") 79 | plt.plot(x_clean, label="Actual signal") 80 | plt.plot(x, label="Actual signal with noise") 81 | plt.legend() 82 | 83 | plt.figure(3) 84 | plt.clf() 85 | plt.title("Observed Signal") 86 | plt.plot(b) 87 | 88 | plt.figure(4) 89 | plt.clf() 90 | plt.title("Reconstruction from M = " + str(M) + " measurements.") 91 | plt.plot(ground_truth, label="Ground Truth") 92 | plt.plot(y_omp, label="Reconstruction from OMP") 93 | plt.plot(y_fista, label="Reconstruction from FISTA") 94 | plt.plot(y_stela, label="Reconstruction from STELA") 95 | plt.legend() 96 | # 97 | plt.figure(5) 98 | plt.clf() 99 | plt.title("Phase transition for sparsity k = " + str(k)) 100 | plt.plot(M_phase_transition / N, success_rate, label="Sucess rate of OMP") 101 | plt.xlabel("compression ratio M/N") 102 | plt.ylabel("Sucess rate") 103 | plt.legend() 104 | plt.show() 105 | -------------------------------------------------------------------------------- /test/algorithm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2023 Sebastian Semper, Christoph Wagner 3 | # https://www.tu-ilmenau.de/it-ems/ 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | import unittest 17 | 18 | import numpy as np 19 | import fastmat as fm 20 | import fastmat.algorithms as fma 21 | 22 | class TestAlgorithm(unittest.TestCase): 23 | def test_Baseclass(self): 24 | # Construct a simple CS problem to test for correct support retrieval 25 | numN, numM, numK = 100, 40, 6 26 | A = fm.Matrix(np.random.randn(numM, numN)) 27 | alg = fma.OMP(A, numMaxSteps=numK) 28 | idx_support = np.random.choice(numN, numK, replace=False) 29 | x = np.zeros((numN, )) 30 | x[idx_support] = np.random.randn(numK) 31 | b = A * x 32 | 33 | # Setup tracing the steps of the algorithm 34 | def printResult(instance): 35 | print(instance) 36 | 37 | alg.cbTrace = fma.Algorithm.snapshot 38 | alg.cbResult = printResult 39 | 40 | # Run the setting and query the collected trace, once before and after 41 | alg.trace 42 | y = alg.process(b) 43 | alg.trace 44 | 45 | # Try clearing the trace 46 | self.assertRaises(TypeError, lambda: setattr(alg, 'trace', None)) 47 | self.assertRaises(TypeError, lambda: setattr(alg, 'trace', ())) 48 | self.assertRaises(TypeError, lambda: setattr(alg, 'trace', {})) 49 | self.assertRaises(TypeError, lambda: setattr(alg, 'trace', 1)) 50 | alg.trace = [] 51 | 52 | # Try setting some gibberish and some legit parameters 53 | self.assertRaises( 54 | AttributeError, lambda: alg.updateParameters(numBla=123) 55 | ) 56 | alg.updateParameters(numMaxSteps=numK) 57 | 58 | np.testing.assert_array_equal( 59 | np.sort(np.squeeze(np.nonzero(np.squeeze(y)))), 60 | np.sort(np.squeeze(idx_support)) 61 | ) 62 | np.testing.assert_allclose( 63 | np.squeeze(y), np.squeeze(x), rtol=1e-12, atol=1e-15 64 | ) 65 | 66 | # Check that the abstract base class is protected 67 | self.assertRaises(NotImplementedError, fma.Algorithm) 68 | 69 | # retrieve the memory footprint of the algorithm 70 | alg.nbytes 71 | 72 | 73 | def test_OMP(self): 74 | numN, numM, numB = 100, 40, 7 75 | arrM = np.random.randn(numM, numN) 76 | self.assertRaises(TypeError, lambda: fma.OMP(arrM)) 77 | self.assertRaises(TypeError, lambda: fma.OMP(None)) 78 | 79 | alg = fma.OMP(fm.Matrix(arrM), numMaxSteps=7) 80 | arrB = np.random.randn(numM, ) 81 | alg.process(arrB) 82 | alg.process(np.random.randn(numM, numB)) 83 | self.assertRaises( 84 | ValueError, lambda: alg.process(np.random.randn(numM, numM, numB)) 85 | ) 86 | self.assertRaises(ValueError, lambda: alg.process(np.zeros(()))) 87 | 88 | alg.updateParameters(numMaxSteps=0) 89 | self.assertRaises(ValueError, lambda: alg.process(arrB)) 90 | alg.updateParameters(numMaxSteps=-123) 91 | self.assertRaises(ValueError, lambda: alg.process(arrB)) 92 | -------------------------------------------------------------------------------- /fastmat/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | r""" 19 | In many fields of engineering linear transforms play a key role during modeling 20 | and solving real world problems. Often these linear transforms have an inherent 21 | structure which reduces the degrees of freedom in their parametrization. 22 | Moreover, this structure allows to describe the action of a linear mapping on a 23 | given vector more efficiently than the general one. 24 | 25 | This structure can be exploited twofold. First, the storage of these transforms 26 | in form of matrices, on computers normally an array of numbers in 27 | :math:`\mathbb{C}` or :math:`\mathbb{R}`, might be unnecessary. 28 | So for each structure there is a more concise way of representation, which 29 | leads to a benefit in memory consumption when using these linear transforms. 30 | Second, the structure allows more efficient calculations when applying the 31 | linear transform to a vector. This may result in a drop in algorithmic 32 | complexity which implies that computing time can be saved. 33 | 34 | Still, these structural benefits have to be exploited and it is not often easy 35 | to accomplish this in a save and reuseable way. Moreover, in applications you 36 | often think of the linear transforms as a matrix and your way of working with 37 | it is streamlined to this way of thinking, which is only natural, but does not 38 | directly allow to exploit the structure. 39 | 40 | So, there are different ways of thinking in what is natural and in what is 41 | efficient. This is the gap fastmat tries to bridge by allowing you to work with 42 | the provided objects as if they were common matrices represented as arrays of 43 | numbers, while the algorithms that make up the internals are highly adapted to 44 | the specific structure at hand. It provides you with a set of tools to work 45 | with linear transforms while hiding the algorithmic complexity and exposing the 46 | benefits in memory and calculation efficiency without too much overhead. 47 | 48 | This way you can worry about really urgent matters to you, like research and 49 | development of algorithms and leave the internals to fastmat. 50 | """ 51 | 52 | # import fundamental types and classes first, also behavioural flags 53 | from .Matrix import Matrix, Hermitian, Conjugate, Transpose, flags 54 | from .Matrix import Inverse, PseudoInverse 55 | from .Product import Product 56 | 57 | # import all fastmat classes 58 | from .BlockDiag import BlockDiag 59 | from .Blocks import Blocks 60 | from .Circulant import Circulant 61 | from .Diag import Diag 62 | from .DiagBlocks import DiagBlocks 63 | from .Eye import Eye 64 | from .Fourier import Fourier 65 | from .Hadamard import Hadamard 66 | from .Kron import Kron 67 | from .LFSRCirculant import LFSRCirculant 68 | from .LowRank import LowRank 69 | from .Outer import Outer 70 | from .Parametric import Parametric 71 | from .Partial import Partial 72 | from .Permutation import Permutation 73 | from .Polynomial import Polynomial 74 | from .Sparse import Sparse 75 | from .Sum import Sum 76 | from .Toeplitz import Toeplitz 77 | from .Zero import Zero 78 | 79 | # define package version (gets overwritten by setup script) 80 | from .version import __version__ 81 | 82 | # compile a list of all matrix classes offered by the package 83 | 84 | 85 | def isClass(item): 86 | try: 87 | return issubclass(item, Matrix) 88 | except TypeError: 89 | return False 90 | 91 | 92 | classes = list(item for item in locals().values() if isClass(item)) 93 | -------------------------------------------------------------------------------- /doc/examples/compressed-sensing.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | import fastmat as fm 5 | import fastmat.algorithms as fma 6 | 7 | # Problem dimensions 8 | compression_factor = 4 9 | N = 60 # Problem size 10 | M = int(N / compression_factor) # Number of observations 11 | k = 3 # sparsity level 12 | noise_power_db = -10. 13 | 14 | # Ground truth of scenario 15 | # We choose the ground_truth to be two dimensional here to align all vectors 16 | # explicitly vertical, allowing easy stacking later on 17 | ground_truth_positions = np.random.choice(N, k) 18 | ground_truth_weights = np.random.randn(k, 1) 19 | ground_truth = np.zeros((N, 1)) 20 | ground_truth[ground_truth_positions] = ground_truth_weights 21 | 22 | 23 | # Set up the linear signal model and reconstruction method, 24 | # consisting of Measurement Matrix `Phi` and Signal Base `Dict` 25 | Phi = fm.Matrix(np.random.randn(M, N)) 26 | Dict = fm.Fourier(N) 27 | 28 | A = Phi * Dict 29 | 30 | 31 | # Now determine the actual (real-world) signal and its observation 32 | # according to the specified Measurement matrix and plot the signals 33 | # also allow for noise 34 | 35 | 36 | def add_noise(signal, pwr_db): 37 | return signal + 10**(pwr_db / 10.) * np.linalg.norm(signal) * ( 38 | np.random.randn(*signal.shape) / np.sqrt(signal.size) 39 | ) 40 | 41 | 42 | x_clean = Dict * ground_truth 43 | x = add_noise(x_clean, noise_power_db) 44 | b = Phi * x 45 | 46 | # Now reconstruct the original ground truth using 47 | # * Orthogonal Matching Pursuit (OMP) 48 | # * Fast Iterative Shrinkage Thresholding Algorithm (FISTA) 49 | # * Soft-Thresholding with simplified Exact Line search Algorithm (STELA) 50 | numLambda = 5 51 | numSteps = 600 52 | alg_omp = fma.OMP(A, numMaxSteps=k) 53 | alg_fista = fma.FISTA(A, numMaxSteps=numSteps, numLambda=numLambda) 54 | alg_stela = fma.STELA(A, numMaxSteps=numSteps, numLambda=numLambda) 55 | y_omp = alg_omp.process(b) 56 | y_fista = alg_fista.process(b) 57 | y_stela = alg_stela.process(b) 58 | 59 | # Setup a simple phase transition diagram for OMP, for a number of randomly 60 | # chosen measurement matrices and another number of noise realizations for 61 | # each measurement matrix. 62 | trials = 15 63 | M_phase_transition = np.arange(k, N) 64 | true_support = (ground_truth == 0) 65 | success_rate = np.zeros(len(M_phase_transition)) 66 | for index, m_phase_transition in enumerate(M_phase_transition): 67 | for _ in range(trials): 68 | # randomly choose a new measurement matrix 69 | Phi_pt = fm.Matrix(np.random.randn(m_phase_transition, N)) 70 | alg_omp = fma.OMP(Phi_pt * Dict, numMaxSteps=k) 71 | 72 | # randomly choose `trials` different noise realizations 73 | x_pt = add_noise(np.tile(x_clean, (1, trials)), noise_power_db) 74 | b_pt = Phi_pt * x_pt 75 | 76 | # and process recovery all in one flush 77 | recovered_support = alg_omp.process(b_pt) 78 | 79 | # now determine the success of our recovery and update the success rate 80 | success = (recovered_support == 0.) == true_support 81 | success_rate[index] += np.mean(np.all(success, axis=0)) 82 | 83 | print(success_rate[index]) 84 | 85 | # finally, normalize the success_rate to the amount of trials performed 86 | success_rate = success_rate / trials 87 | 88 | # Plot all results 89 | plt.figure(1) 90 | plt.clf() 91 | plt.title('Ground Truth') 92 | plt.plot(ground_truth) 93 | 94 | plt.figure(2) 95 | plt.clf() 96 | plt.title('Actual Signal') 97 | plt.plot(x_clean, label='Actual signal') 98 | plt.plot(x, label='Actual signal with noise') 99 | plt.legend() 100 | 101 | plt.figure(3) 102 | plt.clf() 103 | plt.title('Observed Signal') 104 | plt.plot(b) 105 | 106 | plt.figure(4) 107 | plt.clf() 108 | plt.title("Reconstruction from M = " + str(M) + " measurements.") 109 | plt.stem(ground_truth_positions, ground_truth_weights, label='Ground Truth') 110 | plt.plot(y_omp, label='Reconstruction from OMP') 111 | plt.plot(y_fista, label='Reconstruction from FISTA') 112 | plt.plot(y_stela, label='Reconstruction from STELA') 113 | plt.legend() 114 | # 115 | plt.figure(5) 116 | plt.clf() 117 | plt.title("Phase transition for sparsity k = " + str(k)) 118 | plt.plot(1. * M_phase_transition / N, success_rate, label='Sucess rate of OMP') 119 | plt.xlabel('compression ratio M/N') 120 | plt.ylabel('Sucess rate') 121 | plt.legend() 122 | plt.show() 123 | -------------------------------------------------------------------------------- /fastmat/Eye.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import numpy as np 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | from .core.cmath cimport _arrZero 24 | 25 | cdef class Eye(Matrix): 26 | r""" 27 | 28 | For :math:`x \in \mathbb{C}^n` we 29 | 30 | map .. math:: 31 | x \mapsto x. 32 | 33 | note:: 34 | Eye.forward(x) returns the exact same object as the given input array x. 35 | Make sure to issue an explicit .copy() in case you need it! 36 | 37 | The identity matrix only needs the dimension :math:`n` of the vectors it 38 | acts on. 39 | 40 | >>> # import the package 41 | >>> import fastmat 42 | >>> # set the parameter 43 | >>> n = 10 44 | >>> # construct the identity 45 | >>> I = fastmat.Eye(n) 46 | 47 | This yields the identity matrix :math:`I_{10}` with dimension :math:`10`. 48 | """ 49 | 50 | def __init__(self, order, **options): 51 | ''' 52 | Initialize Identity (Eye) matrix instance. 53 | 54 | Parameters 55 | ---------- 56 | order : int 57 | Size of the desired identity matrix [order x order]. 58 | 59 | **options : optional 60 | Additional keyworded arguments. Supports all optional arguments 61 | supported by :py:class:`fastmat.Matrix`. 62 | ''' 63 | self._initProperties(order, order, np.int8, **options) 64 | 65 | cpdef np.ndarray _getArray(Eye self): 66 | ''' 67 | Return an explicit representation of the matrix as numpy-array. 68 | ''' 69 | return np.eye(self.numRows, dtype=self.dtype) 70 | 71 | ############################################## class property override 72 | cpdef np.ndarray _getCol(self, intsize idx): 73 | cdef np.ndarray arrRes 74 | 75 | arrRes = _arrZero(1, self.numRows, 1, self.numpyType) 76 | arrRes[idx] = 1 77 | 78 | return arrRes 79 | 80 | cpdef np.ndarray _getRow(self, intsize idx): 81 | return self._getCol(idx) 82 | 83 | cpdef object _getLargestSingularValue(self): 84 | return 1. 85 | 86 | cpdef object _getLargestEigenValue(self): 87 | return 1. 88 | 89 | cpdef object _getItem(self, intsize idxRow, intsize idxCol): 90 | return 1 if (idxRow == idxCol) else 0 91 | 92 | cpdef np.ndarray _getColNorms(self): 93 | return np.ones((self.numCols, ), dtype=self.dtype) 94 | 95 | cpdef np.ndarray _getRowNorms(self): 96 | return np.ones((self.numRows, ), dtype=self.dtype) 97 | 98 | cpdef Matrix _getColNormalized(self): 99 | return self 100 | 101 | cpdef Matrix _getRowNormalized(self): 102 | return self 103 | 104 | cpdef Matrix _getGram(self): 105 | return self 106 | 107 | cpdef Matrix _getT(self): 108 | return self 109 | 110 | cpdef Matrix _getH(self): 111 | return self 112 | 113 | cpdef Matrix _getConj(self): 114 | return self 115 | 116 | ############################################## class property override 117 | cpdef tuple _getComplexity(self): 118 | return (0., 0.) 119 | 120 | ############################################## class forward / backward 121 | cpdef np.ndarray _forward(Eye, np.ndarray arrX): 122 | return arrX 123 | 124 | cpdef np.ndarray _backward(Eye self, np.ndarray arrX): 125 | return arrX 126 | 127 | ############################################## class reference 128 | cpdef np.ndarray _reference(Eye self): 129 | return np.eye(self.numRows, dtype=self.dtype) 130 | 131 | ############################################## class inspection, QM 132 | def _getTest(self): 133 | from .inspect import TEST 134 | return { 135 | TEST.COMMON: { 136 | TEST.NUM_ROWS : 35, 137 | TEST.NUM_COLS : TEST.NUM_ROWS, 138 | TEST.OBJECT : Eye, 139 | TEST.INITARGS : [TEST.NUM_ROWS] 140 | }, 141 | TEST.CLASS: {}, 142 | TEST.TRANSFORMS: {} 143 | } 144 | 145 | def _getBenchmark(self): 146 | from .inspect import BENCH 147 | return { 148 | BENCH.COMMON: { 149 | BENCH.FUNC_GEN : (lambda c: Eye(c)), 150 | }, 151 | BENCH.FORWARD: {}, 152 | BENCH.OVERHEAD: { 153 | BENCH.FUNC_GEN : (lambda c: Eye(2 ** c)), 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /fastmat/Zero.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | cimport numpy as np 19 | import numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.cmath cimport _arrZero 23 | from .core.types cimport * 24 | 25 | 26 | cdef class Zero(Matrix): 27 | 28 | r""" 29 | 30 | 31 | .. math:: 32 | x \mapsto 0 33 | 34 | The zero matrix only needs the dimension :math:`n` of the vectors it acts 35 | on. It is very fast and very good! 36 | 37 | >>> import fastmat as fm 38 | >>> 39 | >>> # define the parameter 40 | >>> n = 10 41 | >>> 42 | >>> # construct the matrix 43 | >>> O = fm.Zero(n) 44 | """ 45 | 46 | def __init__(self, numRows, numCols, **options): 47 | ''' 48 | Initialize Zero matrix instance. 49 | 50 | Parameters 51 | ---------- 52 | numRows : int 53 | Height (row count) of the desired zero matrix. 54 | 55 | numCols : int 56 | Width (column count) of the desired zero matrix. 57 | 58 | **options : optional 59 | Additional keyworded arguments. Supports all optional arguments 60 | supported by :py:class:`fastmat.Matrix`. 61 | ''' 62 | # set properties of matrix 63 | self._initProperties(numRows, numCols, np.int8, **options) 64 | 65 | ############################################## class property override 66 | cpdef np.ndarray _getArray(self): 67 | return _arrZero(2, self.numRows, self.numCols, self.numpyType) 68 | 69 | cpdef np.ndarray _getCol(self, intsize idx): 70 | return _arrZero(1, self.numRows, 1, self.numpyType) 71 | 72 | cpdef np.ndarray _getRow(self, intsize idx): 73 | return _arrZero(1, self.numCols, 1, self.numpyType) 74 | 75 | cpdef object _getItem(self, intsize idxRow, intsize idxCol): 76 | return 0 77 | 78 | cpdef object _getLargestEigenValue(self): 79 | return 0. 80 | 81 | cpdef object _getLargestSingularValue(self): 82 | return 0. 83 | 84 | cpdef Matrix _getT(self): 85 | return Zero(self.numCols, self.numRows) 86 | 87 | cpdef Matrix _getH(self): 88 | return Zero(self.numCols, self.numRows) 89 | 90 | cpdef Matrix _getConj(self): 91 | return self 92 | 93 | cpdef Matrix _getGram(self): 94 | return Zero(self.numCols, self.numCols) 95 | 96 | cpdef np.ndarray _getColNorms(self): 97 | return np.zeros((self.numCols, ), dtype=self.dtype) 98 | 99 | cpdef np.ndarray _getRowNorms(self): 100 | return np.zeros((self.numRows, ), dtype=self.dtype) 101 | 102 | ############################################## class property override 103 | cpdef tuple _getComplexity(self): 104 | return (self.numRows, self.numCols) 105 | 106 | ############################################## class forward / backward 107 | cpdef np.ndarray _forward(self, np.ndarray arrX): 108 | return _arrZero( 109 | arrX.ndim, self.numRows, arrX.shape[1] if arrX.ndim > 1 else 1, 110 | getNumpyType(arrX)) 111 | 112 | cpdef np.ndarray _backward(self, np.ndarray arrX): 113 | return _arrZero( 114 | arrX.ndim, self.numCols, arrX.shape[1] if arrX.ndim > 1 else 1, 115 | getNumpyType(arrX)) 116 | 117 | ############################################## class reference 118 | cpdef np.ndarray _reference(self): 119 | return np.zeros((self.numRows, self.numCols), dtype=self.dtype) 120 | 121 | ############################################## class inspection, QM 122 | def _getTest(self): 123 | from .inspect import TEST, dynFormat 124 | return { 125 | TEST.COMMON: { 126 | TEST.NUM_ROWS : 35, 127 | TEST.NUM_COLS : TEST.Permutation([30, TEST.NUM_ROWS]), 128 | TEST.OBJECT : Zero, 129 | TEST.INITARGS : [TEST.NUM_ROWS, TEST.NUM_COLS], 130 | TEST.NAMINGARGS : dynFormat( 131 | "%dx%d", TEST.NUM_ROWS, TEST.NUM_COLS 132 | ) 133 | }, 134 | TEST.CLASS: {}, 135 | TEST.TRANSFORMS: {} 136 | } 137 | 138 | def _getBenchmark(self): 139 | from .inspect import BENCH 140 | return { 141 | BENCH.COMMON: { 142 | BENCH.FUNC_GEN : (lambda c: Zero(c, c)), 143 | }, 144 | BENCH.FORWARD: {}, 145 | BENCH.OVERHEAD: { 146 | BENCH.FUNC_GEN : (lambda c: Zero(2 ** c, 2 ** c)), 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /fastmat/core/types.pxd: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import cython 19 | import numpy as np 20 | cimport numpy as np 21 | 22 | ################################################## define unique type-id types 23 | 24 | ctypedef np.uint8_t ftype 25 | ctypedef np.uint8_t ntype 26 | ctypedef np.npy_intp intsize 27 | 28 | ################################################## define global fused types 29 | # 30 | # fastmat-wide definitions of fused types which specify the datatypes allowed 31 | # in memoryviews of ndarrays. 32 | # 33 | # Fused types work in a way that each argument of each fused type used as 34 | # parameters must be of the same explicit type. i.e. if a function accepts 35 | # two parameters of the same-named fused type (allowing float and double), 36 | # then both of these parameters must either be float or double and no combina- 37 | # tions between these types are allowed. To allow combinations, each parameter 38 | # must have its own fused type, even if they contain the same definitions. 39 | # Further, these types also must not be derived from other fused types. 40 | 41 | # WARNING: be sure to keep the NUM_TYPES definition in types.h correct! 42 | cdef extern from "types.h": 43 | enum: NUM_TYPES 44 | 45 | ctypedef enum TYPES: 46 | TYPE_INT8 47 | TYPE_INT16 48 | TYPE_INT32 49 | TYPE_INT64 50 | TYPE_FLOAT32 51 | TYPE_FLOAT64 52 | TYPE_COMPLEX64 53 | TYPE_COMPLEX128 54 | TYPE_INVALID 55 | TYPE_NUM 56 | 57 | ################################ fused type classes 58 | 59 | ctypedef fused TYPE_INT: 60 | np.int8_t 61 | np.int16_t 62 | np.int32_t 63 | np.int64_t 64 | 65 | ctypedef fused TYPE_REAL: 66 | np.float32_t 67 | np.float64_t 68 | 69 | ctypedef fused TYPE_COMPLEX: 70 | np.complex64_t 71 | np.complex128_t 72 | 73 | ctypedef fused TYPE_FLOAT: 74 | np.float32_t 75 | np.float64_t 76 | np.complex64_t 77 | np.complex128_t 78 | 79 | ctypedef fused TYPE_ALL: 80 | np.int8_t 81 | np.int16_t 82 | np.int32_t 83 | np.int64_t 84 | np.float32_t 85 | np.float64_t 86 | np.complex64_t 87 | np.complex128_t 88 | 89 | 90 | ################################ one round of fused types for input arguments 91 | ctypedef fused TYPE_IN: 92 | np.int8_t 93 | np.int16_t 94 | np.int32_t 95 | np.int64_t 96 | np.float32_t 97 | np.float64_t 98 | np.complex64_t 99 | np.complex128_t 100 | 101 | ctypedef fused TYPE_IN_R: 102 | np.int8_t 103 | np.int16_t 104 | np.int32_t 105 | np.int64_t 106 | np.float32_t 107 | np.float64_t 108 | 109 | ctypedef fused TYPE_IN_I: 110 | np.int8_t 111 | np.int16_t 112 | np.int32_t 113 | np.int64_t 114 | 115 | 116 | ################################ one round of fused types for operand arguments 117 | ctypedef fused TYPE_OP: 118 | np.int8_t 119 | np.int16_t 120 | np.int32_t 121 | np.int64_t 122 | np.float32_t 123 | np.float64_t 124 | np.complex64_t 125 | np.complex128_t 126 | 127 | ctypedef fused TYPE_OP_R: 128 | np.int8_t 129 | np.int16_t 130 | np.int32_t 131 | np.int64_t 132 | np.float32_t 133 | np.float64_t 134 | 135 | ctypedef fused TYPE_OP_I: 136 | np.int8_t 137 | np.int16_t 138 | np.int32_t 139 | np.int64_t 140 | 141 | 142 | ################################ type information structures 143 | 144 | ctypedef struct INFO_TYPE_s: 145 | ntype numpyType 146 | ftype fusedType 147 | ftype *promote 148 | np.float64_t eps 149 | np.float64_t min 150 | np.float64_t max 151 | int dsize 152 | bint isNumber 153 | bint isInt 154 | bint isFloat 155 | bint isComplex 156 | 157 | 158 | ################################################## type handling 159 | 160 | cdef INFO_TYPE_s typeInfo[NUM_TYPES] 161 | cdef ftype typeSelection[ np.NPY_NTYPES] 162 | 163 | cdef INFO_TYPE_s * getTypeInfo(object) except * 164 | 165 | cpdef ntype getNumpyType(object obj) except * 166 | cpdef ftype getFusedType(object obj) except * 167 | cpdef np.float64_t getTypeEps(object obj) except * 168 | cpdef np.float64_t getTypeMin(object obj) except * 169 | cpdef np.float64_t getTypeMax(object obj) except * 170 | cpdef bint isInteger(object obj) except * 171 | cpdef bint isFloat(object obj) except * 172 | cpdef bint isComplex(object obj) except * 173 | 174 | ################################################## type Promotion stuff 175 | 176 | cdef ftype promoteFusedTypes(ftype, ftype) except * 177 | cpdef object safeTypeExpansion(object) 178 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # fastmat documentation build configuration file, created by 5 | # sphinx-quickstart on Thu Nov 16 16:18:06 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | print(sys.version) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | # 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [ 34 | 'sphinx.ext.autodoc', 35 | 'sphinx.ext.autosectionlabel', 36 | 'sphinx.ext.doctest', 37 | 'sphinx.ext.todo', 38 | 'sphinx.ext.coverage', 39 | 'sphinx.ext.mathjax', 40 | 'sphinx.ext.githubpages', 41 | 'sphinx.ext.autosummary', 42 | 'matplotlib.sphinxext.plot_directive', 43 | 'numpydoc' 44 | ] 45 | 46 | # Add any paths that contain templates here, relative to this directory. 47 | templates_path = ['_templates'] 48 | 49 | # The suffix(es) of source filenames. 50 | # You can specify multiple suffix as a list of string: 51 | # 52 | # source_suffix = ['.rst', '.md'] 53 | source_suffix = '.rst' 54 | 55 | # The master toctree document. 56 | master_doc = 'index' 57 | 58 | # General information about the project. 59 | project = 'fastmat' 60 | copyright = '2018, Sebastian Semper, Christoph Wagner' 61 | author = 'Sebastian Semper, Christoph Wagner' 62 | 63 | # The version info for the project you're documenting, acts as replacement for 64 | # |version| and |release|, also used in various other places throughout the 65 | # built documents. 66 | # 67 | # The short X.Y version. 68 | with open("../.version", "r") as f: 69 | lines = [str(s) for s in [ln.strip() for ln in f] if len(s)] 70 | version = lines[0] 71 | 72 | # The full version, including alpha/beta/rc tags. 73 | release = version 74 | 75 | print("Building docs for version %s" %(version, )) 76 | # The language for content autogenerated by Sphinx. Refer to documentation 77 | # for a list of supported languages. 78 | # 79 | # This is also used if you do content translation via gettext catalogs. 80 | # Usually you set "language" from the command line for these cases. 81 | language = None 82 | 83 | # List of patterns, relative to source directory, that match files and 84 | # directories to ignore when looking for source files. 85 | # This patterns also effect to html_static_path and html_extra_path 86 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 87 | 88 | # The name of the Pygments (syntax highlighting) style to use. 89 | pygments_style = 'sphinx' 90 | 91 | # If true, `todo` and `todoList` produce output, else they produce nothing. 92 | todo_include_todos = True 93 | 94 | 95 | # -- Options for HTML output ---------------------------------------------- 96 | 97 | # The theme to use for HTML and HTML Help pages. See the documentation for 98 | # a list of builtin themes. 99 | # 100 | html_theme = 'sphinx_rtd_theme' 101 | 102 | html_theme_options = { 103 | "collapse_navigation": False 104 | } 105 | 106 | html_logo = "_static/gfx/logo_short.png" 107 | html_favicon = "_static/gfx/logo_favicon.png" 108 | 109 | # Theme options are theme-specific and customize the look and feel of a theme 110 | # further. For a list of options available for each theme, see the 111 | # documentation. 112 | # 113 | # html_theme_options = {} 114 | 115 | # Add any paths that contain custom static files (such as style sheets) here, 116 | # relative to this directory. They are copied after the builtin static files, 117 | # so a file named "default.css" will overwrite the builtin "default.css". 118 | html_static_path = ['_static'] 119 | 120 | 121 | # -- Options for HTMLHelp output ------------------------------------------ 122 | 123 | # Output file base name for HTML help builder. 124 | htmlhelp_basename = 'fastmatdoc' 125 | 126 | 127 | # -- Options for Texinfo output ------------------------------------------- 128 | 129 | # Grouping the document tree into Texinfo files. List of tuples 130 | # (source start file, target name, title, author, 131 | # dir menu entry, description, category) 132 | texinfo_documents = [ 133 | (master_doc, 'fastmat', 'fastmat Documentation', 134 | author, 'fastmat', 'Fast Linear Transforms in Python', 135 | 'Miscellaneous'), 136 | ] 137 | 138 | numpydoc_show_class_members = False 139 | class_members_toctree = False 140 | 141 | 142 | def skip(app, what, name, obj, skip, options): 143 | if name == "__init__": 144 | return False 145 | return skip 146 | 147 | 148 | def setup(app): 149 | app.connect("autodoc-skip-member", skip) 150 | app.add_stylesheet('custom.css') 151 | -------------------------------------------------------------------------------- /fastmat/Permutation.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import numpy as np 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .core.types cimport * 23 | from .core.cmath cimport _arrSqueezedCopy 24 | 25 | cdef class Permutation(Matrix): 26 | 27 | r""" 28 | 29 | For a given permutation :math:`\sigma \in S_n` and a vector 30 | :math:`x \in \mathbb{C}^n` we map 31 | 32 | .. math:: 33 | x \mapsto \left(x_{\sigma(i)}\right)_{i = 1}^n. 34 | 35 | >>> # import the package 36 | >>> import fastmat 37 | >>> 38 | >>> # set the permutation 39 | >>> sigma = np.array([3,1,2,0]) 40 | >>> 41 | >>> # construct the identity 42 | >>> P = fastmat.Permutation(sigma) 43 | 44 | .. math:: 45 | J = \begin{bmatrix} 46 | 0 & 0 & 0 & 1 \\ 47 | 0 & 1 & 0 & 0 \\ 48 | 0 & 0 & 1 & 0 \\ 49 | 1 & 0 & 0 & 0 50 | \end{bmatrix} 51 | """ 52 | 53 | property sigma: 54 | r"""Return the defining permutation 55 | 56 | *(read only)* 57 | """ 58 | 59 | def __get__(self): 60 | return self._sigma 61 | 62 | def __init__(self, sigma, **options): 63 | ''' 64 | Initialize a Permutation matrix instance. 65 | 66 | Parameters 67 | ---------- 68 | sigma : :py:class:`numpy.ndarray` 69 | A 1d vector of type int mapping the row indices to column indices 70 | uniquely. 71 | 72 | **options : optional 73 | Additional keyworded arguments. Supports all optional arguments 74 | supported by :py:class:`fastmat.Matrix`. 75 | ''' 76 | if not isinstance(sigma, np.ndarray): 77 | sigma = np.array(sigma) 78 | 79 | self._sigma = _arrSqueezedCopy(sigma) 80 | if (sigma.ndim != 1) or (self._sigma.ndim != 1): 81 | raise ValueError( 82 | "Diag: Definition vector must have exactly one dimension.") 83 | 84 | numRows = sigma.shape[0] 85 | if not np.allclose(np.sort(sigma), np.arange(numRows)): 86 | raise ValueError("Not a permutation.") 87 | 88 | self._tau = np.argsort(sigma) 89 | self._initProperties(numRows, numRows, np.int8, **options) 90 | 91 | ############################################## class property override 92 | cpdef object _getItem(self, intsize idxRow, intsize idxCol): 93 | return 1 if (self._sigma[idxRow] == idxCol) else 0 94 | 95 | cpdef np.ndarray _getArray(self): 96 | return np.eye(self.numRows, dtype=self.dtype)[self.sigma, :] 97 | 98 | cpdef object _getLargestSingularValue(self): 99 | return 1. 100 | 101 | cpdef object _getLargestEigenValue(self): 102 | return 1. 103 | 104 | cpdef np.ndarray _getColNorms(self): 105 | return np.ones((self.numCols, ), dtype=self.dtype) 106 | 107 | cpdef np.ndarray _getRowNorms(self): 108 | return np.ones((self.numRows, ), dtype=self.dtype) 109 | 110 | cpdef Matrix _getColNormalized(self): 111 | return self 112 | 113 | cpdef Matrix _getRowNormalized(self): 114 | return self 115 | 116 | ############################################## class property override 117 | cpdef tuple _getComplexity(self): 118 | return (self.numRows, self.numCols) 119 | 120 | ############################################## class forward / backward 121 | cpdef np.ndarray _forward(self, np.ndarray arrX): 122 | return arrX[self._sigma, :] 123 | 124 | cpdef np.ndarray _backward(self, np.ndarray arrX): 125 | return arrX[self._tau, :] 126 | 127 | ############################################## class reference 128 | cpdef np.ndarray _reference(self): 129 | return np.eye(self.numRows, dtype=self.dtype)[self._sigma, :] 130 | 131 | ############################################## class inspection, QM 132 | def _getTest(self): 133 | from .inspect import TEST 134 | return { 135 | TEST.COMMON: { 136 | TEST.NUM_ROWS : 35, 137 | TEST.NUM_COLS : TEST.NUM_ROWS, 138 | TEST.OBJECT : Permutation, 139 | TEST.INITARGS : ( 140 | lambda param: [np.random.permutation(param[TEST.NUM_ROWS])] 141 | ) 142 | }, 143 | TEST.CLASS: {}, 144 | TEST.TRANSFORMS: {} 145 | } 146 | 147 | def _getBenchmark(self): 148 | from .inspect import BENCH 149 | return { 150 | BENCH.COMMON: { 151 | BENCH.FUNC_GEN : (lambda c: 152 | Permutation(np.random.permutation(c))) 153 | }, 154 | BENCH.FORWARD: {}, 155 | BENCH.OVERHEAD: { 156 | BENCH.FUNC_GEN : (lambda c: 157 | Permutation(np.random.permutation(2 ** c))) 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /fastmat/core/resource.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import sys 19 | from itertools import chain 20 | from collections import deque 21 | import numpy as np 22 | from scipy.sparse import spmatrix 23 | from ..Matrix import Matrix 24 | 25 | ################################################## getMemoryFootprint() 26 | 27 | 28 | def getMemoryFootprint(obj, **options): 29 | """Return the total memory consumption of a python object including objects 30 | nested withing that object. 31 | 32 | If one nested object is referenced multiple times within the object 33 | hierarchy of `obj`, it is inspected and accounted for only once. 34 | 35 | The contents of the following builtin containers and their subclasses are 36 | analyzed: 37 | * :py:class:`object` (publicly accessible python-properties only) 38 | * :py:class:`tuple` 39 | * :py:class:`list` 40 | * :py:class:`dict` 41 | * :py:class:`deque` 42 | * :py:class:`set` 43 | * :py:class:`frozenset`. 44 | 45 | Note: Only onjects represented in the python namespace the object spans can 46 | be inspected and accounted for in the memory consumption figure 47 | returned by this call. This explicitly does exclude low-level fields, 48 | fixed- and variable sized arrays, pointers and other constructs that 49 | may be compiled into an Extension-Type object but cannot be inspected 50 | by python at runtime. 51 | 52 | Parameters 53 | ---------- 54 | obj : object 55 | The python object for which the total memory consumption shall be 56 | determined. 57 | 58 | verbose : bool, optional 59 | Be verbose while inspecting `obj`. This results in size and hierarchy 60 | information about objects inspected being printed out to STDOUT. 61 | 62 | Returns 63 | ------- 64 | int 65 | Total memory consumption in bytes of `obj`, including nested objects. 66 | 67 | """ 68 | # extract options 69 | verbose = options.get('verbose', False) 70 | 71 | # keep track of object ids already seen 72 | seen = set() 73 | 74 | # estimate size of objects without __sizeof__() 75 | default_size = sys.getsizeof(0) 76 | 77 | # setup handlers for various data types 78 | from ..algorithms.Algorithm import Algorithm 79 | all_handlers = { 80 | tuple: iter, 81 | list: iter, 82 | deque: iter, 83 | dict: lambda d: chain.from_iterable(d.items()), 84 | set: iter, 85 | frozenset: iter, 86 | } 87 | 88 | # walker for getting size of object considering corner and special cases 89 | def sizeof(obj): 90 | # skip objects already seen once 91 | if id(obj) in seen: 92 | return 0 93 | 94 | seen.add(id(obj)) 95 | 96 | s = sys.getsizeof(obj, default_size) 97 | 98 | # check fastmat matrices: 99 | # only cdefs with explicit `public` tag will be seen here ! 100 | if isinstance(obj, Matrix): 101 | for key in dir(obj): 102 | if key[0] == '_' and key[1] != '_': 103 | item = getattr(obj, key) 104 | if not callable(item) and (item is not None): 105 | s += sizeof(item) 106 | 107 | # check for ndarrays (have special properties holding data) 108 | elif isinstance(obj, np.ndarray): 109 | if obj.base is not None: 110 | # add memory size of base (if not yet added) 111 | # some numpy versions don't report properly to getsizeof() 112 | added = sizeof(obj.base) 113 | return s + added if added > s else s 114 | 115 | # some numpy versions don't report properly to getsizeof() 116 | added = obj.nbytes 117 | s += added if added > s else 0 118 | 119 | # check fastmat algorithm: 120 | # only cdefs with explicit `public` tag will be seen here ! 121 | elif isinstance(obj, Algorithm): 122 | for key in dir(obj): 123 | if not key.startswith('_') and key != 'nbytes': 124 | item = getattr(obj, key) 125 | if not callable(item) and (item is not None): 126 | s += sizeof(item) 127 | 128 | # check for sparse arrays (have special properties holding data) 129 | elif isinstance(obj, spmatrix): 130 | s += sizeof(obj.__dict__) 131 | else: 132 | # check for other known container types 133 | for typ, handler in all_handlers.items(): 134 | if isinstance(obj, typ): 135 | s += sum(map(sizeof, handler(obj))) 136 | break 137 | 138 | if verbose: 139 | print("..%d, [%s@%x]" %(s, type(obj), id(obj))) 140 | 141 | return s 142 | 143 | size = sizeof(obj) 144 | if verbose: 145 | print('Total: %d bytes in %d objects referenced by %s' %( 146 | size, len(seen), repr(obj))) 147 | 148 | return size 149 | -------------------------------------------------------------------------------- /doc/architecture/types.rst: -------------------------------------------------------------------------------- 1 | .. Copyright 2016 Sebastian Semper, Christoph Wagner 2 | https://www.tu-ilmenau.de/it-ems/ 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | .. _types: 17 | 18 | Data Types in fastmat 19 | ===================== 20 | 21 | To achieve high performance, fastmat is designed to support common data types 22 | only, namely 23 | 24 | * Floating point with single and double precision (`float32` and `float64`) 25 | * Complex floating point with single and double precision (`complex64` and 26 | `complex128`) 27 | * Signed integer of selected fixed sizes (`int8`, `int16`, `int32`, `int64`) 28 | 29 | Some implementation of fastmat matrices use numpy under the hood. Although 30 | those could technically be able to deal with other data types offered by 31 | ``numpy`` as well, using other types than those listed above is disencouraged. 32 | This is important to ensure consistency throughout the intestines of 33 | ``fastmat``, which is important for being able to reliably test the package. 34 | 35 | The following sections detail the organization and handling of types in 36 | ``fastmat`` and explain the mechanisms how fastmat handles type promotion. The 37 | final section references the internal type API of ``fastmat``. 38 | 39 | Type handling 40 | ------------- 41 | 42 | **ftype** 43 | 44 | To distinguish between the supported data types ``fastmat`` uses the ``ftype`` 45 | internally as type identifier. All data type checks within the package as well 46 | as the type promotion logic is internally handled via these type numbers, that 47 | correspond directly to the associated ``numpy.dtype`` given in this table: 48 | 49 | +--------------------------+------------------+-------------------+-------+ 50 | | Data Type | ``numpy.dtype`` | fastmat ``ftype`` | Short | 51 | +--------------------------+------------------+-------------------+-------+ 52 | | Signed Integer 8 bit | ``int8_t`` | 0 | i8 | 53 | | Signed Integer 16 bit | ``int16_t`` | 1 | i16 | 54 | | Signed Integer 32 bit | ``int32_t`` | 2 | i32 | 55 | | Signed Integer 64 bit | ``int64_t`` | 3 | i64 | 56 | | Single-precision Float | ``float32_t`` | 4 | f32 | 57 | | Double-Precision Float | ``float64_t`` | 5 | f64 | 58 | | Single-Precision Complex | ``complex64_t`` | 6 | c64 | 59 | | Double-Precision Complex | ``complex128_t`` | 7 | c128 | 60 | +--------------------------+------------------+-------------------+-------+ 61 | 62 | Type promotion 63 | -------------- 64 | 65 | Type promotion matrix of binary operators of kind ``f(A, B)`` as used 66 | throughout ``fastmat``: 67 | 68 | +--------------------+-------------------------------------------------------+ 69 | | | B | 70 | | +---------------------------+-------------+-------------+ 71 | | Type promotion | int | float | complex | 72 | | +------+------+------+------+------+------+------+------+ 73 | | | i8 | i16 | i32 | i64 | f32 | f64 | c64 | c128 | 74 | +---+----------------+------+------+------+------+------+------+------+------+ 75 | | | int 8 | i8 | i16 | i32 | i64 | f32 | f64 | c64 | c128 | 76 | | +----------------+------+------+------+------+------+------+------+------+ 77 | | | int 16 | i16 | i16 | i32 | i64 | f32 | f64 | c64 | c128 | 78 | | +----------------+------+------+------+------+------+------+------+------+ 79 | | | int 32 | i32 | i32 | i32 | i64 | f64 | f64 | c128 | c128 | 80 | | +----------------+------+------+------+------+------+------+------+------+ 81 | | | int 64 | i64 | i64 | i64 | i64 | f64 | f64 | c128 | c128 | 82 | | A +----------------+------+------+------+------+------+------+------+------+ 83 | | | float 32 | f32 | f32 | f64 | f64 | f64 | f64 | c128 | c128 | 84 | | +----------------+------+------+------+------+------+------+------+------+ 85 | | | float 64 | f64 | f64 | f64 | f64 | f64 | f64 | c128 | c128 | 86 | | +----------------+------+------+------+------+------+------+------+------+ 87 | | | complex 64 | c64 | c64 | c128 | c128 | c64 | c128 | c64 | c128 | 88 | | +----------------+------+------+------+------+------+------+------+------+ 89 | | | complex 128 | c128 | c128 | c128 | c128 | c128 | c128 | c128 | c128 | 90 | +---+----------------+------+------+------+------+------+------+------+------+ 91 | 92 | Example: 93 | The forward operator of a :py:class:`fastmat.Matrix` of type `float 32` 94 | will, if provided with an `int 32` input vector, yield an output vector of 95 | type `float 64`. 96 | 97 | .. Note:: 98 | The output data type will be expanded to fit the mantissa of any of the 99 | operands best. As `int 32` has a wider mantissa than `float 32` offers, 100 | the example type promotion will yield `float 64` to maintain accuracy. 101 | 102 | .. Note:: 103 | Data types will not be expanded automatically to the next larger data 104 | type for the sake of preventing overflows. You'll need to specifically 105 | expand the data type -- where necessary -- by specifying ``minType=?`` 106 | during the generation of your :py:class:`fastmat.Matrix` instance. 107 | 108 | 109 | ``fastmat.core.types`` 110 | ---------------------- 111 | 112 | .. automodule:: fastmat.core.types 113 | :members: 114 | :undoc-members: 115 | :show-inheritance: 116 | -------------------------------------------------------------------------------- /PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.1 2 | Name: fastmat 3 | Version: 0.1 4 | Summary: fast linear transforms in Python 5 | Home-page: https://ems-tu-ilmenau.github.io/fastmat/ 6 | Author: Christoph Wagner, Sebastian Semper, EMS group TU Ilmenau 7 | Author-email: christoph.wagner@tu-ilmenau.de 8 | License: Apache Software License 9 | Description: # fastmat 10 | 11 | ## Description 12 | Scientific computing requires handling large composed or structured matrices. 13 | Fastmat is a framework for handling large composed or structured matrices. 14 | It allows expressing and using them in a mathematically intuitive way while 15 | storing and handling them internally in an efficient way. This approach allows 16 | huge savings in computational time and memory requirements compared to using 17 | dense matrix representations. 18 | 19 | ### Languages 20 | - Python 21 | - Cython 22 | 23 | ### Dependencies 24 | - Python >= 2.7 or >=3.4 25 | - Numpy >= 1.7 26 | - Scipy >= 1.0 27 | - Cython >= 0.29 28 | - setuptools >= 18.0 29 | 30 | ### Authors 31 | - Sebastian Semper - Technische Universität Ilmenau, Institute for Mathematics 32 | - Christoph Wagner - Technische Universität Ilmenau, 33 | Institute for Information Technology, EMS Group 34 | 35 | ### Contact 36 | - sebastian.semper@tu-ilmenau.de 37 | - christoph.wagner@tu-ilmenau.de 38 | - https://www.tu-ilmenau.de/it-ems/ 39 | 40 | ## Documentation / HELP ! 41 | Please have a look at the documentation, which is included in the source 42 | distribution at github or may be built locally on your machine by running 43 | `make doc` 44 | 45 | If you experience any trouble please do not hesitate to contact us or to open 46 | an issue on our github projectpage: https://github.com/EMS-TU-Ilmenau/fastmat 47 | 48 | ### FAQ 49 | 50 | #### Installation fails with *ImportError: No module named Cython.Build* 51 | Something went wrong with resolving the dependencies of fastmat during setup. 52 | Unfortunately one or more of the required packages numpy, scipy or cython were 53 | not installed automatically. Please do this manually by running 54 | `pip install cython numpy scipy matplotlib` 55 | and try the installation of fastmat again. 56 | 57 | #### Issue not resolved? 58 | Please contact us or leave your bug report in the *issue* section. Thank You! 59 | 60 | 61 | ## Citation / Acknowledgements 62 | If you want to use fastmat or parts of it in your private, scientific or 63 | commercial project or work you are required to acknowledge visibly to all users 64 | that fastmat was used for your work and put a reference to the project and the 65 | EMS Group at TU Ilmenau. 66 | 67 | If you use fastmat for your scientific work you are further required to cite 68 | the following publication affiliated with the project: 69 | - `to be announced soon. Please tune back in regularly to check on updates.` 70 | 71 | ## Installation 72 | fastmat currently **supports both Linux and Windows**. Building the 73 | documentation and running benchmarks is currently only supported under linux 74 | with windows support underway. You may choose one of these installation methods: 75 | 76 | ### installation with pip: the fast and easy way 77 | 78 | fastmat is included in the Python Package Index (PyPI) and can be installed 79 | from the commandline by running one easy and straightforward command: 80 | `pip install fastmat` 81 | 82 | When installing with pip all dependencies of the package will be installed 83 | along. 84 | 85 | ### installation from source: doing it manually 86 | - download the source distribution from our github repository: 87 | https://github.com/EMS-TU-Ilmenau/fastmat/archive/master.zip 88 | - unpack its contents and navigate to the project root directory 89 | - make sure you have installed all listed dependencies with at least the 90 | specified version 91 | - type `make install` to install fastmat on your computer 92 | * If you intend to install the package locally for your user 93 | type `make install MODE=--user` instead. 94 | * If you only would like to compile the package to use it from this local 95 | directory without installing it, type `make compile` 96 | 97 | 98 | ## Demos 99 | Feel free to have a look at the demos in the `demo/` directory of the source 100 | distribution. Please make sure to have fastmat already installed when running 101 | these. 102 | 103 | Please note that the edgeDetect demo requires the Python Imaging Library (PIL) 104 | installed and the SAFT demos do compile a cython-core of a user defined matrix 105 | class beforehand thus having a delaying the first time they're executed. 106 | 107 | Keywords: linear transforms efficient algorithms mathematics 108 | Platform: UNKNOWN 109 | Classifier: Development Status :: 5 - Production/Stable 110 | Classifier: Intended Audience :: Developers 111 | Classifier: Intended Audience :: Education 112 | Classifier: Intended Audience :: Science/Research 113 | Classifier: License :: OSI Approved :: Apache Software License 114 | Classifier: Natural Language :: English 115 | Classifier: Programming Language :: Python 116 | Classifier: Programming Language :: Python :: 2 117 | Classifier: Programming Language :: Python :: 2.7 118 | Classifier: Programming Language :: Python :: 3 119 | Classifier: Programming Language :: Python :: 3.5 120 | Classifier: Programming Language :: Python :: 3.6 121 | Classifier: Programming Language :: Python :: 3.7 122 | Classifier: Programming Language :: Python :: 3.8 123 | Classifier: Programming Language :: Python :: 3.9 124 | Classifier: Programming Language :: Python :: 3.10 125 | Classifier: Programming Language :: Python :: 3.11 126 | Classifier: Programming Language :: Python :: 3.12 127 | Classifier: Topic :: Scientific/Engineering :: Mathematics 128 | Classifier: Topic :: Software Development :: Libraries 129 | -------------------------------------------------------------------------------- /fastmat/algorithms/Algorithm.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | import numpy as np 20 | cimport numpy as np 21 | 22 | from copy import copy 23 | #from cpython.object cimport PyObject_GenericSetAttr 24 | from ..core.resource import getMemoryFootprint 25 | 26 | ################################################################################ 27 | ################################################## class Algorithm 28 | cdef class Algorithm(object): 29 | r"""Algorithm Base Class 30 | 31 | The baseclass of all algorithms that operate on Matrices. This abstract 32 | baseclass introduces general framework concepts such as interfaces for 33 | parameter specification, algorithm execution, logging and callbacks. 34 | 35 | >>> algI = fma.ISTA(Fourier(10)) 36 | >>> algI.cbResult = lambda i: print(i.arrResult) 37 | >>> algI.cbStep = lambda i: print(i.numStep) 38 | >>> algI.cbTrace = fma.Algorithm.snapshot 39 | >>> algI.process(np.ones(10) + np.random.randn(10)) 40 | >>> plt.imshow(np.hstack((np.abs(tt.arrX) for tt in algI.trace))) 41 | >>> plt.show() 42 | """ 43 | 44 | def __init__(self): 45 | if type(self) is Algorithm: 46 | raise NotImplementedError( 47 | "Algorithm baseclass cannot be instantiated." 48 | ) 49 | 50 | property cbTrace: 51 | def __get__(self): 52 | return self._cbTrace 53 | 54 | def __set__(self, value): 55 | self._cbTrace = value 56 | 57 | property cbResult: 58 | def __get__(self): 59 | return self._cbResult 60 | 61 | def __set__(self, value): 62 | self._cbResult = value 63 | 64 | property trace: 65 | def __get__(self): 66 | if self._trace is None: 67 | self._trace = [] 68 | 69 | return self._trace 70 | 71 | def __set__(self, value): 72 | if not isinstance(value, list): 73 | raise TypeError("Algorithm trace must be a list") 74 | 75 | self._trace = value 76 | 77 | ############################################## algorithm resource handling 78 | # nbytes - Property(read) 79 | # Size of the Matrix object 80 | property nbytes: 81 | # r"""Number of bytes in memory used by this instance 82 | # """ 83 | def __get__(self): 84 | return getMemoryFootprint(self) 85 | 86 | # def __setattr__(self, attr, val): 87 | # try: 88 | # PyObject_GenericSetAttr(self, attr, val) 89 | # except AttributeError: 90 | # if self.__dict__ is None: 91 | # self.__dict__ = {} 92 | # 93 | # self.__dict__[attr] = val 94 | # print("bla") 95 | 96 | def updateParameters(self, **kwargs): 97 | r""" 98 | Update the parameters of the algorithm instance with the supllied 99 | keyworded arguments. 100 | 101 | Apply the set of parameters specified in kwargs by iteratively passing 102 | them to setattr(self, ...). Specifying an parameter which does not have 103 | a mathing attribute in the algorithm class will cause an AttributeError 104 | to be raised. 105 | """ 106 | if getattr(self, '_attributes', None) is None: 107 | # This is the first updateParameters call and is supposed to hold 108 | # the initial parameters. Since we do not know if the user might 109 | # add some extra parameters, we take the set of here-supplied 110 | # parameters as the set of allowed parameters. 111 | self._attributes = kwargs.copy() 112 | 113 | for key, value in kwargs.items(): 114 | if not hasattr(self, key) and (self._attributes is not None and 115 | key not in self._attributes): 116 | raise AttributeError( 117 | "Attribute '%s' not defined in %s" %( 118 | key, self.__class__.__name__) 119 | ) 120 | 121 | setattr(self, key, value) 122 | 123 | def process(self, np.ndarray arrB, **kwargs): 124 | r""" 125 | Process an array of data by the algorithm. 126 | 127 | This method also accepts passing additional parameters as keyworded 128 | arguments. These arguments will be applied to the algorithm instance 129 | using self.updateParameters(). 130 | 131 | If no additional parameters are required the self._process() method 132 | may also be called directly for slightly higher call performance. 133 | """ 134 | self.updateParameters(**kwargs) 135 | 136 | # perform the actual computation and service the result callback 137 | arrResult = self._process(arrB) 138 | self.handleCallback(self.cbResult) 139 | 140 | return arrResult 141 | 142 | cpdef np.ndarray _process(self, np.ndarray arrB): 143 | r""" 144 | Process an array of data by the algorithm. 145 | 146 | Please check out self.process() for further information. 147 | """ 148 | # Raise an not implemented Error as this is an (abstract) baseclass. 149 | raise NotImplementedError("Algorithm is not implemented yet.") 150 | 151 | cpdef snapshot(self): 152 | r""" 153 | Add the current instances' state (without the trace) to the trace. 154 | """ 155 | # temporarily remove the trace from the object to allow copying 156 | # without circular references. Then put the trace back in 157 | cdef list trace 158 | trace, self._trace = self._trace, [] 159 | if trace is None: 160 | trace = [] 161 | 162 | trace.append(copy(self)) 163 | self._trace = trace 164 | 165 | cpdef handleCallback(self, callback): 166 | r""" 167 | Call the callback if it is not None. 168 | """ 169 | if callback is not None: 170 | return callback(self) 171 | 172 | return None 173 | -------------------------------------------------------------------------------- /fastmat/DiagBlocks.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | #cython: boundscheck=False, wraparound=False 4 | # Copyright 2018 Sebastian Semper, Christoph Wagner 5 | # https://www.tu-ilmenau.de/it-ems/ 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | ''' 19 | TODO: 20 | - DiagBlocks should simply skip all Zero Matrices (flag them as "None")? 21 | ''' 22 | import numpy as np 23 | cimport numpy as np 24 | 25 | from .Matrix cimport Matrix 26 | 27 | 28 | ################################################################################ 29 | ################################################## class DiagBlocks 30 | cdef class DiagBlocks(Matrix): 31 | r""" 32 | 33 | For given :math:`n,m \in \mathbb{N}` this class allows to define a block 34 | matrix :math:`M \in \mathbb{C}^{nm \times nm}`, where each block is a 35 | diagonal matrix :math:`D_{ij} \in \mathbb{C}^{m \times m}`. This obviously 36 | allows efficient storage and computations. 37 | 38 | >>> # import the package 39 | >>> import fastmat as fm 40 | >>> # define the sizes 41 | >>> n,m = 2, 42 | >>> # define the diagonals 43 | >>> d = np.random.randn( 44 | >>> n, 45 | >>> n, 46 | >>> m) 47 | >>> # define the block 48 | >>> # matrix diagonal-wise 49 | >>> M = fm.DiagBlocks(d) 50 | 51 | We have randomly drawn the defining elements :math:`d` from a standard 52 | Gaussian distribution, which results in 53 | 54 | .. math:: 55 | M = 56 | \begin{bmatrix} 57 | d_{1,1,1} & & & d_{1,2,1} & & \\ 58 | & d_{1,1,2} & & & d_{1,2,2} & \\ 59 | & & d_{1,1,3} & & & d_{1,2,3} \\ 60 | d_{2,1,1} & & & d_{2,2,1} & & \\ 61 | & d_{2,1,2} & & & d_{2,2,2} & \\ 62 | & & d_{2,1,3} & & & d_{2,2,3} \\ 63 | \end{bmatrix}. 64 | """ 65 | 66 | ############################################## class methods 67 | def __init__(self, tenDiags, **options): 68 | ''' 69 | Initialize DiagBlocks matrix instance. 70 | 71 | Parameters 72 | ---------- 73 | tenDiags : :py:class:`numpy.ndarray` 74 | The generating 3d-array of the flattened diagonal tensor this 75 | matrix describes. The matrix data type is determined by the data 76 | type of this array. 77 | 78 | **options : optional 79 | Additional keyworded arguments. Supports all optional arguments 80 | supported by :py:class:`fastmat.Matrix`. 81 | ''' 82 | 83 | self._numDiagsRows = tenDiags.shape[0] 84 | self._numDiagsCols = tenDiags.shape[1] 85 | self._numDiagsSize = tenDiags.shape[2] 86 | 87 | cdef intsize numRows = self._numDiagsRows * self._numDiagsSize 88 | cdef intsize numCols = self._numDiagsCols * self._numDiagsSize 89 | 90 | self._tenDiags = np.copy(tenDiags) 91 | 92 | dataType = tenDiags.dtype 93 | 94 | # set properties of matrix 95 | self._cythonCall = True 96 | self._initProperties(numRows, numCols, dataType, **options) 97 | self._widenInputDatatype = True 98 | 99 | ############################################## class property override 100 | cpdef tuple _getComplexity(self): 101 | 102 | return (0, 0) 103 | 104 | ############################################## class forward / backward 105 | cpdef _forwardC( 106 | self, 107 | np.ndarray arrX, 108 | np.ndarray arrRes, 109 | ftype typeX, 110 | ftype typeRes 111 | ): 112 | arrRes[:] = np.einsum( 113 | 'nmz,zmk -> znk', 114 | self._tenDiags, 115 | arrX.reshape((-1, self._numDiagsCols, arrX.shape[1]), order='F') 116 | ).reshape((-1, arrX.shape[1]), order='F') 117 | 118 | cpdef _backwardC( 119 | self, 120 | np.ndarray arrX, 121 | np.ndarray arrRes, 122 | ftype typeX, 123 | ftype typeRes 124 | ): 125 | arrRes[:] = np.einsum( 126 | 'mnz,zmk -> znk', 127 | self._tenDiags.conj(), 128 | arrX.reshape((-1, self._numDiagsCols, arrX.shape[1]), order='F') 129 | ).reshape((-1, arrX.shape[1]), order='F') 130 | 131 | ############################################## class reference 132 | cpdef np.ndarray _reference(self): 133 | cdef np.ndarray arrRes 134 | 135 | arrRes = np.zeros((self.numRows, self.numCols), dtype=self.dtype) 136 | 137 | for nn in range(self._numDiagsRows): 138 | for mm in range(self._numDiagsCols): 139 | arrRes[ 140 | nn *self._numDiagsSize: 141 | (nn +1) *self._numDiagsSize, 142 | mm *self._numDiagsSize: 143 | (mm +1) *self._numDiagsSize 144 | ] = np.diag(self._tenDiags[nn, mm, :]) 145 | 146 | return arrRes 147 | 148 | ############################################## class inspection, QM 149 | def _getTest(self): 150 | from .inspect import TEST, dynFormat 151 | return { 152 | TEST.COMMON: { 153 | 'size' : 4, 154 | TEST.NUM_ROWS : 32, 155 | TEST.NUM_COLS : 32, 156 | 'mType' : TEST.Permutation(TEST.ALLTYPES), 157 | 'arr' : TEST.ArrayGenerator({ 158 | TEST.DTYPE : 'mType', 159 | TEST.SHAPE : (8, 8, 4) 160 | }), 161 | TEST.INITARGS : (lambda param : [param['arr']()]), 162 | TEST.OBJECT : DiagBlocks, 163 | TEST.NAMINGARGS : dynFormat("(%dx%d) each", 164 | 'size', 'size') 165 | }, 166 | TEST.CLASS: {}, 167 | TEST.TRANSFORMS: {} 168 | } 169 | 170 | def _getBenchmark(self): 171 | from .inspect import BENCH 172 | 173 | return { 174 | BENCH.FORWARD: { 175 | BENCH.FUNC_GEN : (lambda c: DiagBlocks( 176 | np.random.randn(c, c, 64) 177 | )), 178 | BENCH.FUNC_SIZE : (lambda c: 64 * c) 179 | }, 180 | BENCH.OVERHEAD: { 181 | BENCH.FUNC_GEN : (lambda c: DiagBlocks( 182 | np.random.randn(2 ** c, 2 ** c, c) 183 | )), 184 | BENCH.FUNC_SIZE : (lambda c: 2 ** c * c) 185 | } 186 | } 187 | -------------------------------------------------------------------------------- /.github/workflows/build-dev-pr.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: test deployment to stable branch 5 | 6 | on: 7 | pull_request: 8 | branches: [ "stable" ] 9 | 10 | push: 11 | branches: [ "stable" ] 12 | 13 | workflow_dispatch: 14 | 15 | env: 16 | ARTIFACT: wheelhouse/* dist/* 17 | CIBW_SKIP: pp* cp2* *musl* *ppc* *s390x 18 | 19 | jobs: 20 | ############################################################################### 21 | build_wheel_x86_x64: 22 | name: Build ${{ matrix.cibw-build }} on x64_x86 ${{ matrix.os }} using Python ${{ matrix.python-version }} 23 | runs-on: ${{ matrix.os }} 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | os: ["ubuntu-latest", "windows-latest", "macos-latest"] 28 | # python-version: ["3.7", "3.9", "3.10", "3.11"] 29 | python-version: ["3.9", "3.10", "3.12"] 30 | include: 31 | # # Numpy C-API 0x12 32 | # - python-version: "3.7" 33 | # cibw-build: "cp35*" 34 | # cibw-archs-linux: "x86_64 i686" 35 | # cibw-archs-macos: "x86_64" 36 | # cibw-archs-windows: "AMD64 x86" 37 | # pip-requires: "cython>=0.29 numpy==1.16.3 scipy==1.1.0 cibuildwheel==1.1 twine" 38 | # Numpy C-API 0x13 39 | - python-version: "3.9" 40 | cibw-build: "cp36* cp37* cp38* cp39*" 41 | cibw-archs-linux: "x86_64 i686" 42 | cibw-archs-macos: "x86_64" 43 | cibw-archs-windows: "AMD64 x86" 44 | pip-requires: "cython>=0.29 numpy==1.19.3 scipy==1.5.4 cibuildwheel==1.9 twine" 45 | # Numpy C-API 0x14 46 | - python-version: "3.10" 47 | cibw-build: "cp310*" 48 | cibw-archs-linux: "x86_64" 49 | cibw-archs-macos: "x86_64" 50 | cibw-archs-windows: "AMD64" 51 | pip-requires: "cython>=0.29 numpy==1.21.6 scipy==1.7.3 cibuildwheel==2.12.1 twine" 52 | # Numpy C-API 0x16 53 | - python-version: "3.12" 54 | cibw-build: "cp311* cp312*" 55 | cibw-archs-linux: "x86_64" 56 | cibw-archs-macos: "x86_64" 57 | cibw-archs-windows: "AMD64" 58 | pip-requires: "cython>=0.29 numpy==1.26.4 scipy==1.12.0 cibuildwheel==2.17.0 twine" 59 | 60 | steps: 61 | - uses: actions/checkout@v3 62 | - name: Set up Python ${{ matrix.python-version }} 63 | uses: actions/setup-python@v3 64 | with: 65 | python-version: ${{ matrix.python-version }} 66 | - name: Build the wheels 67 | env: 68 | CIBW_BUILD: ${{ matrix.cibw-build }} 69 | CIBW_ARCHS_LINUX: ${{ matrix.cibw-archs-linux }} 70 | CIBW_ARCHS_MACOS: ${{ matrix.cibw-archs-macos }} 71 | CIBW_ARCHS_WINDOWS: ${{ matrix.cibw-archs-windows }} 72 | CIBW_ENVIRONMENT: "FASTMAT_COMPILER_OPTIONS=-march=x86-64 -mtune=core2" 73 | CIBW_BEFORE_BUILD: "python -m pip install --only-binary :all: ${{ matrix.pip-requires }}" 74 | run: | 75 | python -m pip install --upgrade pip 76 | python -m pip install --only-binary :all: ${{ matrix.pip-requires }} 77 | cibuildwheel --output-dir wheelhouse 78 | 79 | - uses: actions/upload-artifact@v3 80 | with: 81 | path: ./wheelhouse/*.whl 82 | 83 | - name: Upload the Results 84 | shell: bash 85 | run: | 86 | ls -l wheelhouse 87 | if [[ ${{ github.event_name }} == "push" ]]; then 88 | echo "Uploading to pypi" 89 | elif [[ ${{ github.event_name }} == "pull_request" ]]; then 90 | echo "Testing build" 91 | fi 92 | 93 | ############################################################################### 94 | build_wheel_macos_arm64: 95 | name: Build ${{ matrix.cibw-build }} on arm64 ${{ matrix.os }} using Python ${{ matrix.python-version }} 96 | runs-on: ${{ matrix.os }} 97 | strategy: 98 | fail-fast: false 99 | matrix: 100 | os: ["macos-latest"] 101 | python-version: ["3.9", "3.10", "3.12"] 102 | include: 103 | # Numpy C-API 0x13 104 | - python-version: "3.9" 105 | cibw-build: "cp36* cp37* cp38* cp39*" 106 | cibw-archs-macos: "arm64" 107 | pip-requires: "cython>=0.29 numpy==1.19.3 scipy==1.5.4 cibuildwheel==1.9 twine" 108 | # Numpy C-API 0x14 109 | - python-version: "3.10" 110 | cibw-build: "cp310*" 111 | cibw-archs-macos: "arm64" 112 | pip-requires: "cython>=0.29 numpy==1.21.6 scipy==1.7.3 cibuildwheel==2.12.1 twine" 113 | # Numpy C-API 0x16 114 | - python-version: "3.12" 115 | cibw-build: "cp311* cp312*" 116 | cibw-archs-macos: "arm64" 117 | pip-requires: "cython>=0.29 numpy==1.26.4 scipy==1.12.0 cibuildwheel==2.17.0 twine" 118 | 119 | steps: 120 | - uses: actions/checkout@v3 121 | - name: Set up Python ${{ matrix.python-version }} 122 | uses: actions/setup-python@v3 123 | with: 124 | python-version: ${{ matrix.python-version }} 125 | - name: Build the wheels 126 | # shell: bash 127 | env: 128 | CIBW_BUILD: ${{ matrix.cibw-build }} 129 | CIBW_ARCHS_LINUX: ${{ matrix.cibw-archs-linux }} 130 | CIBW_ARCHS_MACOS: ${{ matrix.cibw-archs-macos }} 131 | CIBW_ARCHS_WINDOWS: ${{ matrix.cibw-archs-windows }} 132 | CIBW_ENVIRONMENT: "FASTMAT_COMPILER_OPTIONS=-mcpu=apple-m1" 133 | CIBW_BEFORE_BUILD: "python -m pip install --only-binary :all: ${{ matrix.pip-requires }}" 134 | run: | 135 | python -m pip install --upgrade pip 136 | python -m pip install --only-binary :all: ${{ matrix.pip-requires }} 137 | clang -v 138 | cibuildwheel --output-dir wheelhouse 139 | 140 | - uses: actions/upload-artifact@v3 141 | with: 142 | path: ./wheelhouse/*.whl 143 | 144 | - name: Upload the Results 145 | shell: bash 146 | run: | 147 | ls -l wheelhouse 148 | if [[ ${{ github.event_name }} == "push" ]]; then 149 | echo "Uploading to pypi" 150 | elif [[ ${{ github.event_name }} == "pull_request" ]]; then 151 | echo "Testing build" 152 | fi 153 | 154 | ############################################################################### 155 | build_sdist: 156 | name: Build source distribution 157 | runs-on: ubuntu-latest 158 | strategy: 159 | matrix: 160 | python-version: ["3.11"] 161 | 162 | steps: 163 | - uses: actions/checkout@v3 164 | 165 | - uses: actions/setup-python@v3 166 | name: Install Python 167 | with: 168 | python-version: ${{ matrix.python-version }} 169 | 170 | - name: Install cibuildwheel and build sdist 171 | run: | 172 | python -m pip install --upgrade pip 173 | python -m pip install --only-binary :all: cython>=0.29 numpy>=1.16.3 scipy 174 | python setup.py sdist 175 | 176 | - uses: actions/upload-artifact@v3 177 | with: 178 | path: ./dist/*.tar.gz 179 | 180 | - name: Upload the wheels 181 | shell: bash 182 | run: | 183 | ls -l dist 184 | if [[ ${{ github.event_name }} == "push" ]]; then 185 | echo "Uploading to pypi" 186 | elif [[ ${{ github.event_name }} == "pull_request" ]]; then 187 | echo "Testing build" 188 | fi 189 | -------------------------------------------------------------------------------- /fastmat/Diag.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | import numpy as np 19 | cimport numpy as np 20 | 21 | from .Matrix cimport Matrix 22 | from .Eye cimport Eye 23 | from .core.cmath cimport _conjugate, _multiply, _arrZero, _arrSqueezedCopy 24 | from .core.types cimport * 25 | 26 | 27 | ################################################################################ 28 | ################################################## class Diag 29 | cdef class Diag(Matrix): 30 | r""" 31 | 32 | 33 | .. math:: 34 | x \mapsto {\mathrm{diag}}(d_1,\dots,d_n) \cdot x 35 | 36 | A diagonal matrix is uniquely defined by the entries of its diagonal. 37 | 38 | >>> # import the package 39 | >>> import fastmat as fm 40 | >>> import numpy as np 41 | >>> 42 | >>> # build the parameters 43 | >>> n = 4 44 | >>> d = np.array([1, 0, 3, 6]) 45 | >>> 46 | >>> # construct the matrix 47 | >>> D = fm.Diag(d) 48 | 49 | This yields 50 | 51 | .. math:: 52 | d = (1, 0, 3, 6)^\mathrm{T} 53 | 54 | .. math:: 55 | D = \begin{bmatrix} 56 | 1 & & & \\ 57 | & 0 & & \\ 58 | & & 3 & \\ 59 | & & & 6 60 | \end{bmatrix} 61 | """ 62 | 63 | property vecD: 64 | r"""Return the matrix-defining vector of diagonal entries. 65 | 66 | *(read-only)* 67 | """ 68 | 69 | def __get__(self): 70 | return self._vecD 71 | 72 | ############################################## class methods 73 | def __init__(self, vecD, **options): 74 | ''' 75 | Initialize a Diag matrix instance. 76 | 77 | Parameters 78 | ---------- 79 | vecD : :py:class:`numpy.ndarray` 80 | The generating vector of the diagonal entries of this matrix. 81 | 82 | **options : optional 83 | Additional keyworded arguments. Supports all optional arguments 84 | supported by :py:class:`fastmat.Matrix`. 85 | ''' 86 | # store diagonal entry vector as copy of vecD and complain if 87 | # dimension does not match 88 | self._vecD = _arrSqueezedCopy(vecD) 89 | if (vecD.ndim != 1) or (self._vecD.ndim != 1): 90 | raise ValueError( 91 | "Diag: Definition vector must have exactly one dimension.") 92 | 93 | # numRows is size of matrix (and of diagonal vector) 94 | numRows = self._vecD.size 95 | 96 | # set properties of matrix 97 | self._cythonCall = True 98 | self._initProperties(numRows, numRows, self._vecD.dtype, **options) 99 | self._forceContiguousInput = True 100 | self._fortranStyle = True 101 | 102 | ############################################## class property override 103 | cpdef np.ndarray _getCol(self, intsize idx): 104 | cdef np.ndarray arrRes 105 | 106 | arrRes = _arrZero(1, self.numRows, 1, self.numpyType) 107 | arrRes[idx] = self._vecD[idx] 108 | 109 | return arrRes 110 | 111 | cpdef object _getLargestEigenValue(self): 112 | return np.abs(self._vecD).max().astype(np.float64) 113 | 114 | cpdef object _getLargestSingularValue(self): 115 | return np.abs(self._vecD).max().astype(np.float64) 116 | 117 | cpdef np.ndarray _getRow(self, intsize idx): 118 | return self._getCol(idx) 119 | 120 | cpdef object _getItem(self, intsize idxRow, intsize idxCol): 121 | return self._vecD[idxRow] if idxRow == idxCol else self.dtype(0) 122 | 123 | cpdef Matrix _getGram(self): 124 | return Diag(np.abs(self._vecD) ** 2) 125 | 126 | cpdef np.ndarray _getColNorms(self): 127 | return np.abs(self._vecD) 128 | 129 | cpdef np.ndarray _getRowNorms(self): 130 | return np.abs(self._vecD) 131 | 132 | cpdef Matrix _getColNormalized(self): 133 | if typeInfo[self.fusedType].isComplex: 134 | return Diag((self._vecD / np.abs(self._vecD)).astype(self.dtype)) 135 | else: 136 | return Diag(np.sign(self._vecD).astype(self.dtype)) 137 | 138 | cpdef Matrix _getRowNormalized(self): 139 | return self.colNormalized 140 | 141 | cpdef Matrix _getT(self): 142 | return self 143 | 144 | ############################################## class property override 145 | cpdef tuple _getComplexity(self): 146 | return (2. * self.numRows, 3. * self.numRows) 147 | 148 | ############################################## class forward / backward 149 | cpdef _forwardC( 150 | self, 151 | np.ndarray arrX, 152 | np.ndarray arrRes, 153 | ftype typeX, 154 | ftype typeRes 155 | ): 156 | _multiply(arrX, self._vecD, arrRes, 157 | typeX, self.fusedType, typeRes) 158 | 159 | cpdef _backwardC( 160 | self, 161 | np.ndarray arrX, 162 | np.ndarray arrRes, 163 | ftype typeX, 164 | ftype typeRes 165 | ): 166 | _multiply(arrX, _conjugate(self._vecD), arrRes, 167 | typeX, self.fusedType, typeRes) 168 | 169 | ############################################## class reference 170 | cpdef np.ndarray _reference(self): 171 | cdef intsize ii 172 | cdef np.ndarray d = self.vecD 173 | 174 | return np.diag(d) 175 | 176 | ############################################## class inspection, QM 177 | def _getTest(self): 178 | from .inspect import TEST, dynFormat 179 | return { 180 | TEST.COMMON: { 181 | TEST.NUM_ROWS : 35, 182 | TEST.NUM_COLS : TEST.NUM_ROWS, 183 | 'mTypeD' : TEST.Permutation(TEST.ALLTYPES), 184 | TEST.PARAMALIGN : TEST.Permutation(TEST.ALLALIGNMENTS), 185 | 'vecD' : TEST.ArrayGenerator({ 186 | TEST.DTYPE : 'mTypeD', 187 | TEST.SHAPE : (TEST.NUM_ROWS, ), 188 | TEST.ALIGN : TEST.PARAMALIGN 189 | }), 190 | TEST.INITARGS : (lambda param: [param['vecD']()]), 191 | TEST.OBJECT : Diag, 192 | TEST.NAMINGARGS : dynFormat("%s", 'vecD') 193 | }, 194 | TEST.CLASS: {}, 195 | TEST.TRANSFORMS: {} 196 | } 197 | 198 | def _getBenchmark(self): 199 | from .inspect import BENCH 200 | return { 201 | BENCH.COMMON: { 202 | BENCH.FUNC_GEN : (lambda c: Diag(np.random.uniform(2, 3, c))) 203 | }, 204 | BENCH.FORWARD: {}, 205 | BENCH.OVERHEAD: { 206 | BENCH.FUNC_GEN : (lambda c: 207 | Diag(np.random.uniform(2, 3, 2 ** c))) 208 | }, 209 | BENCH.DTYPES: { 210 | BENCH.FUNC_GEN : (lambda c, dt: Diag( 211 | np.random.uniform(2, 3, 2 ** c).astype(dt))) 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fastmat 2 | [![Version](https://img.shields.io/pypi/v/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 3 | [![Status](https://img.shields.io/pypi/status/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 4 | [![fastmat](https://img.shields.io/pypi/dm/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 5 | [![Python wheels](https://img.shields.io/pypi/wheel/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 6 | 7 | [![License](https://img.shields.io/pypi/l/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 8 | [![Python versions](https://img.shields.io/pypi/pyversions/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 9 | 10 | [![Implementation](https://img.shields.io/pypi/implementation/fastmat.svg)](https://pypi.python.org/pypi/fastmat) 11 | [![Coverage Status](https://coveralls.io/repos/github/EMS-TU-Ilmenau/fastmat/badge.svg?branch=master)](https://coveralls.io/github/EMS-TU-Ilmenau/fastmat?branch=master) 12 | [![GitHub issues](https://img.shields.io/github/issues/EMS-TU-Ilmenau/fastmat.svg)](https://github.com/EMS-TU-Ilmenau/fastmat/issues) 13 | [![Documentation Status](https://readthedocs.org/projects/fastmat/badge/?version=latest)](http://fastmat.readthedocs.io/en/latest/?badge=latest) 14 | 15 | ## Description 16 | Scientific computing requires handling large composed or structured matrices. 17 | Fastmat is a framework for handling large composed or structured matrices. 18 | It allows expressing and using them in a mathematically intuitive way while 19 | storing and handling them internally in an efficient way. This approach allows 20 | huge savings in computational time and memory requirements compared to using 21 | dense matrix representations. 22 | 23 | ### Dependencies 24 | - Python 2.7, Python >=3.5 25 | - Numpy >= 1.16.3 26 | - Scipy >= 1.0 27 | - Cython >= 0.29 28 | - soft dependencies: 29 | - matplotlib: for demos and tools that make use of plotting functions 30 | 31 | ### Distribution 32 | Binary wheels are provided for Python >=3.5 for linux, windows and mac, as well as for x86 and ARM architectures. 33 | 34 | For all systems, for which no wheels are provided, you may still install fastmat from the soruce distribution. 35 | 36 | ### Authors & Contact Information 37 | - Sebastian Semper | sebastian.semper@tu-ilmenau.de 38 | Technische Universität Ilmenau, Institute for Mathematics, EMS Group 39 | - Christoph Wagner | christoph.wagner@tu-ilmenau.de 40 | Technische Universität Ilmenau, Institute for Information Technology, EMS Group 41 | - **** 42 | 43 | ## Citation / Acknowledgements 44 | If you use fastmat, or parts of it, for commercial purposes you are required 45 | to acknowledge the use of fastmat visibly to all users of your work and put a 46 | reference to the project and the EMS Group at TU Ilmenau. 47 | 48 | If you use fastmat for your scientific work you are required to mention the 49 | EMS Group at TU Ilmenau and cite the following publication affiliated with the 50 | project: 51 | > Christoph W. Wagner and Sebastian Semper and Jan Kirchhof, _fastmat: Efficient linear transforms in Python_, 52 | > SoftwareX, 2022, https://doi.org/10.1016/j.softx.2022.101013 53 | > 54 | 55 | ``` 56 | @article{Wagner_2022, 57 | doi = {10.1016/j.softx.2022.101013}, 58 | url = {https://doi.org/10.1016%2Fj.softx.2022.101013}, 59 | year = {2022}, 60 | month = {jun}, 61 | publisher = {Elsevier {BV}}, 62 | volume = {18}, 63 | pages = {101013}, 64 | author = {Christoph W. Wagner and Sebastian Semper and Jan Kirchhof}, 65 | title = {fastmat: Efficient linear transforms in Python}, 66 | journal = {{SoftwareX}} 67 | } 68 | ``` 69 | 70 | - **** 71 | 72 | ## Installation 73 | fastmat currently supports Linux, Windows and Mac OS. Lately it also has been 74 | seen on ARM cores coming in a Xilinx ZYNQ FPGA SoC shell. We encourage you to 75 | go ahead trying other platforms as the aforementioned as well and are very 76 | happy if you share your experience with us, allowing us to keep the list 77 | updated. 78 | 79 | ### Installing with pip: 80 | 81 | fastmat is included in the Python Package Index (PyPI) and can be installed 82 | from the commandline by running one easy and straightforward command: 83 | `pip install fastmat` 84 | 85 | When installing with pip all dependencies of the package will be installed 86 | along. With release 0.1.1 python wheels will be offered for many versions 87 | greatly improving installation time and effort. 88 | 89 | #### Bulding from source 90 | 91 | Building binaries has been developed and tested for the use 92 | 93 | ### Manually installing from source 94 | - download the source distribution from our github repository: 95 | https://github.com/EMS-TU-Ilmenau/fastmat/archive/stable.zip 96 | - unpack its contents and navigate to the project root directory 97 | - run `pip install .` to install fastmat on your computer 98 | - you may also install fastmat without pip, using the offered makefile: 99 | * type `make install` to install fastmat on your computer 100 | * If you intend to install the package locally for your user type 101 | `make install MODE=--user` instead 102 | * You may add a version specifier for all `make` targets that directly or indirectly invoke Python: 103 | `make install PYTHON=python2` 104 | `make compile PYTHON=python3` 105 | * If you only would like to compile the package to use it from this local 106 | directory without installing it, type `make compile` 107 | * An uninstallation of a previously run `make install`is possible, provided the installation log file `setup.files` has been preserved 108 | Invoking `make uninstall` without a local `setup.files` causes another installation for generating the setup file log prior to uninstalling 109 | - **NOTE: Windows users** 110 | If you intent on building fastmat from source on a windows platform, make sure you have installed a c compiler environment and make interpreter. One way to accomplish this is to install these tools for Python 2.7 (you may also chose different ones, of course): 111 | * Intel Distribution for Python 2.7 112 | * Microsoft Visual C++ Compiler 9.0 for Python 2.7 113 | * GNU make for Windows 3.81 or newer 114 | * depending on your system: The relevant header files 115 | 116 | ## Demos 117 | Feel free to have a look at the demos in the `demo/` directory of the source 118 | distribution. Please make sure to have fastmat already installed when running 119 | these. 120 | 121 | Please note that the edgeDetect demo requires the Python Imaging Library (PIL) 122 | installed and the SAFT demos do compile a cython-core of a user defined matrix 123 | class beforehand thus having a delaying the first time they're executed. 124 | 125 | ## Documentation / HELP ! 126 | Please have a look at the documentation, which is included in the source 127 | distribution at github or may be built locally on your machine by running 128 | `make doc` 129 | 130 | If you experience any trouble please do not hesitate to contact us or to open 131 | an issue on our github projectpage: https://github.com/EMS-TU-Ilmenau/fastmat 132 | 133 | ### FAQ 134 | 135 | Please check out our project documentation at [readthedocs](https://fastmat.readthedocs.io/). 136 | 137 | #### Windows: Installation fails with various "file not found" errors 138 | Often, this is caused by missing header files. Unfortunately windows ships 139 | without a c-compiler and the header files necessary to compile native binary 140 | code. If you use the Intel Distribution for Python this can be resolved by 141 | installing the Visual Studio Build tools with the version as recommended by 142 | the version of the Intel Distribution for Python that you are using. 143 | 144 | #### Issue not resolved yet? 145 | Please contact us or leave your bug report in the *issue* section. Thank You! 146 | -------------------------------------------------------------------------------- /fastmat/Sparse.pyx: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2018 Sebastian Semper, Christoph Wagner 4 | # https://www.tu-ilmenau.de/it-ems/ 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | cimport numpy as np 19 | import numpy as np 20 | from scipy.sparse import spmatrix 21 | 22 | from .Matrix cimport Matrix 23 | from .core.types cimport * 24 | from .core.cmath cimport _conjugate, _arrSqueeze 25 | 26 | cdef class Sparse(Matrix): 27 | r""" 28 | 29 | 30 | .. math:: 31 | x \mapsto S x, 32 | 33 | where :math:`S` is a ``scipy.sparse`` matrix. To provide a high level of 34 | generality, the user has to make use of the standard ``scipy.sparse`` 35 | matrix constructors and pass them to ``fastmat`` during construction. 36 | After that a ``Sparse`` matrix can be used like every other type in 37 | ``fastmat`` 38 | 39 | >>> # import the package 40 | >>> import fastmat as fm 41 | >>> 42 | >>> # import scipy to get 43 | >>> # the constructor 44 | >>> import scipy.sparse.rand as r 45 | >>> 46 | >>> # set the matrix size 47 | >>> n = 100 48 | >>> 49 | >>> # construct the sparse matrix 50 | >>> S = fm.Sparse( 51 | >>> r( 52 | >>> n, 53 | >>> n, 54 | >>> 0.01, 55 | >>> format='csr' 56 | >>> )) 57 | 58 | This yields a random sparse matrix with 1\% of its entries occupied drawn 59 | from a random distribution. 60 | 61 | It is also possible to directly cast SciPy sparse matrices into the 62 | `fastmat`` sparse matrix format as follows. 63 | 64 | >>> # import the package 65 | >>> import fastmat as fm 66 | >>> 67 | >>> # import scipy to get 68 | >>> # the constructor 69 | >>> import scipy.sparse as ss 70 | >>> 71 | >>> # construct the SciPy sparse matrix 72 | >>> S_scipy = ss.csr_matrix( 73 | >>> [ 74 | >>> [1, 0, 0], 75 | >>> [1, 0, 0], 76 | >>> [0, 0, 1] 77 | >>> ] 78 | >>> ) 79 | >>> 80 | >>> # construct the fastmat sparse matrix 81 | >>> S = fm.Sparse(S_scipy) 82 | 83 | .. note:: 84 | The ``format`` specifier drastically influences performance during 85 | multiplication of these matrices. From our experience ``'csr'`` works 86 | best in these cases. 87 | 88 | For this matrix class we used the already tried and tested routines of 89 | SciPy :ref:`[1]`, so we merely provide a convenient wrapper to 90 | integrate nicely into ``fastmat``. 91 | """ 92 | 93 | property spArray: 94 | r"""Return the scipy sparse matrix . 95 | 96 | *(read only)* 97 | """ 98 | 99 | def __get__(self): 100 | return self._spArray 101 | 102 | property spArrayH: 103 | r"""Return the scipy sparse matrix' hermitian transpose. 104 | 105 | *(read only)* 106 | """ 107 | 108 | def __get__(self): 109 | if self._spArrayH is None: 110 | self._spArrayH = self._spArray.T.conj().tocsr() 111 | return self._spArrayH 112 | 113 | def __init__(self, matSparse, **options): 114 | ''' 115 | Initialize a Sparse matrix instance. 116 | 117 | Parameters 118 | ---------- 119 | matSparse : :py:class:`scipy.sparse.spmatrix` 120 | A 2d scipy sparse matrix to be cast as a fastmat matrix. 121 | 122 | **options : optional 123 | Additional optional keyworded arguments. Supports all optional 124 | arguments supported by :py:class:`fastmat.Matrix`. 125 | ''' 126 | if not isinstance(matSparse, spmatrix): 127 | raise TypeError("Sparse: Use Matrix() for numpy ndarrays." 128 | if isinstance(matSparse, np.ndarray) 129 | else "Sparse: Matrix is not a scipy spmatrix") 130 | 131 | self._spArray = matSparse.tocsr() 132 | 133 | # set properties of matrix 134 | self._initProperties( 135 | self._spArray.shape[0], 136 | self._spArray.shape[1], 137 | self._spArray.dtype, 138 | **options 139 | ) 140 | 141 | cpdef np.ndarray _getArray(self): 142 | return self._spArray.toarray() 143 | 144 | ############################################## class property override 145 | cpdef np.ndarray _getCol(self, intsize idx): 146 | return _arrSqueeze(self._spArray.getcol(idx).toarray()) 147 | 148 | cpdef np.ndarray _getRow(self, intsize idx): 149 | return _arrSqueeze(_conjugate(self.spArrayH.getcol(idx).toarray())) 150 | 151 | cpdef object _getItem(self, intsize idxRow, intsize idxCol): 152 | return self._spArray[idxRow, idxCol] 153 | 154 | ############################################## class property override 155 | cpdef tuple _getComplexity(self): 156 | cdef float complexity = self._spArray.getnnz() 157 | return (complexity, complexity) 158 | 159 | ############################################## class forward / backward 160 | cpdef np.ndarray _forward(self, np.ndarray arrX): 161 | return self._spArray.dot(arrX) 162 | 163 | cpdef np.ndarray _backward(self, np.ndarray arrX): 164 | return self.spArrayH.dot(arrX) 165 | 166 | ############################################## class reference 167 | cpdef np.ndarray _reference(self): 168 | return self._spArray.toarray() 169 | 170 | ############################################## class inspection, QM 171 | def _getTest(self): 172 | from .inspect import TEST, dynFormat, arrSparseTestDist 173 | return { 174 | TEST.COMMON: { 175 | TEST.NUM_ROWS : 25, 176 | TEST.NUM_COLS : TEST.Permutation([30, TEST.NUM_ROWS]), 177 | 'mType' : TEST.Permutation(TEST.ALLTYPES), 178 | 'density' : .1, 179 | TEST.INITARGS : (lambda param: [ 180 | arrSparseTestDist( 181 | (param[TEST.NUM_ROWS], param[TEST.NUM_COLS]), 182 | param['mType'], density=param['density'], 183 | compactFullyOccupied=True 184 | )]), 185 | TEST.OBJECT : Sparse, 186 | 'strType' : (lambda param: TEST.TYPENAME[param['mType']]), 187 | TEST.NAMINGARGS : dynFormat("%s,%s", 'strType', TEST.NUM_COLS) 188 | }, 189 | TEST.CLASS: {}, 190 | TEST.TRANSFORMS: {} 191 | } 192 | 193 | def _getBenchmark(self): 194 | from .inspect import BENCH 195 | import scipy.sparse as sps 196 | return { 197 | BENCH.FORWARD: { 198 | BENCH.FUNC_GEN : (lambda c: Sparse( 199 | sps.rand(c, c, 0.1, format='csr'))) 200 | }, 201 | BENCH.OVERHEAD: { 202 | BENCH.FUNC_GEN : (lambda c: Sparse( 203 | sps.rand(2 ** c, 2 ** c, 0.1, format='csr'))) 204 | }, 205 | BENCH.DTYPES: { 206 | BENCH.FUNC_GEN : (lambda c, dt: ( 207 | Sparse(sps.rand(2 ** c, 2 ** c, 0.1, 208 | format='csr', dtype=dt)) 209 | if isFloat(dt) else None)) 210 | } 211 | } 212 | --------------------------------------------------------------------------------