biPCA 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. bipca/__init__.py +10 -0
  2. bipca/_vendor/__init__.py +0 -0
  3. bipca/_vendor/pyalra/LICENSE +28 -0
  4. bipca/_vendor/pyalra/__init__.py +21 -0
  5. bipca/_vendor/pyalra/alra.py +94 -0
  6. bipca/_vendor/pyalra/choose_k.py +28 -0
  7. bipca/_vendor/pyalra/logging.py +48 -0
  8. bipca/_vendor/pychebfun/LICENSE +11 -0
  9. bipca/_vendor/pychebfun/__init__.py +11 -0
  10. bipca/_vendor/pychebfun/chebfun.py +335 -0
  11. bipca/_vendor/pychebfun/chebfun_init.py +50 -0
  12. bipca/_vendor/pychebfun/plotting.py +180 -0
  13. bipca/_vendor/pychebfun/polyfun.py +415 -0
  14. bipca/base.py +469 -0
  15. bipca/bipca.py +1818 -0
  16. bipca/bipca.py.save +1329 -0
  17. bipca/command_line.py +218 -0
  18. bipca/data_examples.py +607 -0
  19. bipca/experiments/__init__.py +2 -0
  20. bipca/experiments/base.py +3 -0
  21. bipca/experiments/datasets/__init__.py +1 -0
  22. bipca/experiments/datasets/allcools_preprocess.sh +11 -0
  23. bipca/experiments/datasets/base.py +1471 -0
  24. bipca/experiments/datasets/datasets.py +2608 -0
  25. bipca/experiments/datasets/modalities.py +663 -0
  26. bipca/experiments/datasets/plink_preprocess.sh +6 -0
  27. bipca/experiments/datasets/utils.py +162 -0
  28. bipca/experiments/exceptions.py +25 -0
  29. bipca/experiments/experiments.py +809 -0
  30. bipca/experiments/figures/Figure1_Suppfig1.ipynb +42695 -0
  31. bipca/experiments/figures/__init__.py +1 -0
  32. bipca/experiments/figures/base.py +614 -0
  33. bipca/experiments/figures/figures.py +7436 -0
  34. bipca/experiments/figures/plotting_constants.py +114 -0
  35. bipca/experiments/figures/utils.py +264 -0
  36. bipca/experiments/normalizations.py +284 -0
  37. bipca/experiments/types.py +5 -0
  38. bipca/experiments/utils.py +358 -0
  39. bipca/math.py +3845 -0
  40. bipca/plotting.py +1395 -0
  41. bipca/safe_basics.py +555 -0
  42. bipca/utils.py +1350 -0
  43. bipca-1.1.0.dist-info/METADATA +147 -0
  44. bipca-1.1.0.dist-info/RECORD +48 -0
  45. bipca-1.1.0.dist-info/WHEEL +5 -0
  46. bipca-1.1.0.dist-info/entry_points.txt +3 -0
  47. bipca-1.1.0.dist-info/licenses/LICENSE +29 -0
  48. bipca-1.1.0.dist-info/top_level.txt +1 -0
bipca/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ from __future__ import absolute_import
2
+
3
+ from importlib.metadata import version, PackageNotFoundError
4
+
5
+ try:
6
+ __version__ = version("biPCA")
7
+ except PackageNotFoundError:
8
+ __version__ = "unknown"
9
+
10
+ from .bipca import BiPCA
File without changes
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024, Miles Smith
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,21 @@
1
+ """
2
+ .. module:: pyalra
3
+ :platform: Unix, Windows
4
+ :synopsis: Translation of the ALRA R package
5
+
6
+ .. moduleauthor:: Miles Smith <miles-smith@omrf.org>
7
+
8
+ Vendored from https://github.com/milescsmith/pyalra (v1.6.2)
9
+ License: BSD-3-Clause
10
+ """
11
+
12
+ from loguru import logger
13
+
14
+ from bipca._vendor.pyalra.alra import alra
15
+ from bipca._vendor.pyalra.choose_k import choose_k
16
+
17
+ __version__ = "1.6.2"
18
+
19
+ logger.disable("bipca._vendor.pyalra")
20
+
21
+ __all__ = ["alra", "choose_k"]
@@ -0,0 +1,94 @@
1
+ import numpy as np
2
+ import numpy.typing as npt
3
+ import scipy as sp
4
+ from loguru import logger
5
+ from sklearn.utils.extmath import randomized_svd
6
+
7
+ from bipca._vendor.pyalra.choose_k import choose_k
8
+ from bipca._vendor.pyalra.logging import init_logger
9
+
10
+
11
+ def alra(
12
+ a_norm: npt.ArrayLike | sp.sparse.spmatrix,
13
+ k: int = 0,
14
+ q: int = 10,
15
+ quantile_prob: float = 0.001,
16
+ seed: float | None = None,
17
+ debug: bool = False,
18
+ *,
19
+ save_log: bool = False,
20
+ log_level: int = 1,
21
+ ) -> dict[str, npt.ArrayLike]:
22
+ if debug:
23
+ init_logger(log_level, save_log)
24
+
25
+ logger.info(f"Read matrix with {a_norm.shape[0]} cells and {a_norm.shape[1]} genes")
26
+
27
+ if k == 0:
28
+ k, _, u, d, v = choose_k(a_norm)
29
+ logger.info(f"Chose k = {k}")
30
+ else:
31
+ logger.debug("Running rsvd")
32
+ u, d, v = randomized_svd(M=a_norm, n_components=k, n_iter=q, random_state=seed)
33
+
34
+ logger.info("Getting nonzeros\n")
35
+ originally_nonzero = a_norm > 0
36
+
37
+ a_norm_rank_k = u @ np.diag(d) @ v
38
+
39
+ logger.info(f"Find the {quantile_prob} quantile for each gene")
40
+ a_norm_rank_k_mins = np.absolute(np.quantile(a_norm_rank_k, axis=0, q=0.001))
41
+
42
+ logger.info("Sweep")
43
+ a_norm_rank_k_cor = np.zeros(shape=a_norm_rank_k.shape)
44
+ np.copyto(
45
+ dst=a_norm_rank_k_cor,
46
+ src=a_norm_rank_k,
47
+ where=(a_norm_rank_k > np.tile(a_norm_rank_k_mins, (len(a_norm_rank_k), 1))),
48
+ )
49
+
50
+ sigma_1 = np.nanstd(a_norm_rank_k_cor, axis=0)
51
+ sigma_2 = np.nanstd(a_norm, axis=0)
52
+ mu_1 = np.divide(a_norm_rank_k_cor.sum(axis=0), a_norm_rank_k_cor.sum(axis=0))
53
+ mu_2 = np.divide(a_norm.sum(axis=0), (a_norm > 0).sum(axis=0))
54
+
55
+ toscale = np.logical_and(
56
+ np.logical_and(~np.isnan(sigma_1), ~np.isnan(sigma_2)),
57
+ np.logical_and(~np.logical_and((sigma_1 == 0), (sigma_2 == 0)), ~(sigma_1 == 0)),
58
+ )
59
+
60
+ logger.info(f"Scaling all except for {sum(~toscale)} columns")
61
+
62
+ sigma_1_2 = np.divide(sigma_2, sigma_1)
63
+
64
+ toadd = np.add(-np.divide(np.multiply(mu_1, sigma_2), sigma_1), mu_2)
65
+
66
+ a_norm_rank_k_temp = a_norm_rank_k_cor[:, toscale].copy()
67
+ a_norm_rank_k_temp = np.multiply(a_norm_rank_k_temp, sigma_1_2[toscale])
68
+ a_norm_rank_k_temp = np.add(a_norm_rank_k_temp, toadd[toscale])
69
+
70
+ a_norm_rank_k_cor_sc = a_norm_rank_k_cor.copy()
71
+ np.copyto(dst=a_norm_rank_k_cor_sc[:, toscale], src=a_norm_rank_k_temp)
72
+ a_norm_rank_k_cor_sc_zeros = np.zeros_like(a_norm_rank_k_cor_sc)
73
+ np.copyto(dst=a_norm_rank_k_cor_sc, src=a_norm_rank_k_cor_sc_zeros, where=(a_norm_rank_k_cor == 0))
74
+
75
+ lt0 = a_norm_rank_k_cor_sc < 0
76
+ np.copyto(dst=a_norm_rank_k_cor_sc, src=a_norm_rank_k_cor_sc_zeros, where=lt0)
77
+
78
+ a_norm_size = a_norm.shape[0] * a_norm.shape[1]
79
+ logger.info(
80
+ f"{100*np.sum(lt0)/a_norm_size:.2f}% of the values became negative in the scaling process and were set to zero"
81
+ )
82
+
83
+ nonzero_mask = np.logical_and(originally_nonzero, (a_norm_rank_k_cor_sc == 0))
84
+ np.copyto(dst=a_norm_rank_k_cor_sc, src=a_norm, where=nonzero_mask)
85
+
86
+ original_nz = np.sum(a_norm > 0) / a_norm_size
87
+ completed_nz = np.sum(a_norm_rank_k_cor_sc > 0) / a_norm_size
88
+ logger.info(f"The matrix went from {100*original_nz:.2f}% nonzero to {100*completed_nz:.2f}% nonzero")
89
+
90
+ return {
91
+ "A_norm_rank_k": a_norm_rank_k,
92
+ "A_norm_rank_k_cor": a_norm_rank_k_cor,
93
+ "A_norm_rank_k_cor_sc": a_norm_rank_k_cor_sc,
94
+ }
@@ -0,0 +1,28 @@
1
+ import numpy as np
2
+ import numpy.typing as npt
3
+ from sklearn.utils.extmath import randomized_svd
4
+
5
+ # TODO add an option to use pytorch
6
+ def choose_k(
7
+ A_norm: npt.ArrayLike, K: int = 100, thresh: int = 6, noise_start: int = 80, q: int = 2, **kwargs
8
+ ) -> tuple[int, npt.ArrayLike, npt.ArrayLike, npt.ArrayLike, npt.ArrayLike]:
9
+ if K > np.min(A_norm.shape):
10
+ msg = "For an m by n matrix, K must be smaller than the min(m,n)."
11
+ raise ValueError(msg)
12
+ if noise_start > (K - 5):
13
+ msg = "There need to be at least 5 singular values considered noise."
14
+ raise ValueError(msg)
15
+
16
+ noise_svals = list(range(noise_start - 1, K))
17
+ seed = kwargs.get("seed", None)
18
+ u, d, v = randomized_svd(M=A_norm, n_components=K, n_iter=q, random_state=seed)
19
+
20
+ diffs = d[:-1] - d[1:]
21
+
22
+ mu = diffs[np.subtract(noise_svals, 1)].mean()
23
+ sigma = diffs[np.subtract(noise_svals, 1)].std()
24
+ num_of_sds = (diffs - mu) / sigma
25
+
26
+ k = np.where(num_of_sds > thresh)[0].max() + 1
27
+
28
+ return k, num_of_sds, u[:, : k + 1], d[: k + 1], v[: k + 1, :]
@@ -0,0 +1,48 @@
1
+ import datetime
2
+ from sys import stderr
3
+
4
+ from loguru import logger
5
+
6
+
7
+ def init_logger(verbose: int, save_log: bool = True, msg_format: str | None = None) -> None:
8
+ logger.enable("bipca._vendor.pyalra")
9
+ timezone = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
10
+
11
+ try:
12
+ from IPython import get_ipython
13
+
14
+ in_notebook = get_ipython() is not None
15
+ except ImportError:
16
+ in_notebook = False
17
+
18
+ if msg_format is None:
19
+ if in_notebook:
20
+ msg_format = "<green>{name}</green>:<red>{function}</red>:<blue>{line}</blue>·-·<level>{message}</level>"
21
+ else:
22
+ msg_format = "{time:YYYY-MM-DD at HH:mm:ss} | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>·-·<level>{message}</level>"
23
+
24
+ match verbose:
25
+ case 3:
26
+ log_level = "DEBUG" # catches DEBUG, INFO, WARNING, ERROR, CRITICAL, and EXCEPTION
27
+ case 2:
28
+ log_level = "INFO" # catches INFO, WARNING, ERROR, CRITICAL, and EXCEPTION
29
+ case 1:
30
+ log_level = "WARNING" # catches WARNING, ERROR, CRITICAL, and EXCEPTION
31
+ case _:
32
+ log_level = "ERROR" # Catches ERROR, CRITICAL, and EXCEPTION
33
+
34
+ config = {"handlers": [{"sink": stderr, "format": msg_format, "level": log_level}]}
35
+
36
+ if save_log:
37
+ config["handlers"].append(
38
+ {
39
+ "sink": f"pyalra_{datetime.datetime.now(tz=timezone).strftime('%Y-%d-%m--%H-%M-%S')}.log",
40
+ "level": "DEBUG",
41
+ "format": "{time:YYYY-MM-DD at HH:mm:ss} | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>·-·<level>{message}</level>",
42
+ "filter": "bipca._vendor.pyalra",
43
+ "backtrace": True,
44
+ "diagnose": True,
45
+ }
46
+ )
47
+
48
+ logger.configure(**config)
@@ -0,0 +1,11 @@
1
+ Copyright 2017 Olivier Verdier
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,11 @@
1
+ """
2
+ pychebfun - Python Chebyshev Polynomials
3
+
4
+ Vendored from https://github.com/pychebfun/pychebfun (v0.3.0)
5
+ See LICENSE in this directory for copyright and license information.
6
+ """
7
+
8
+ from .chebfun import Chebfun
9
+ from .plotting import compare, plot
10
+
11
+ __all__ = ["Chebfun", "compare", "plot"]
@@ -0,0 +1,335 @@
1
+ #!/usr/bin/env python
2
+ """
3
+ Chebfun module
4
+ ==============
5
+
6
+ .. moduleauthor :: Chris Swierczewski <cswiercz@gmail.com>
7
+ .. moduleauthor :: Olivier Verdier <olivier.verdier@gmail.com>
8
+ .. moduleauthor :: Gregory Potter <ghpotter@gmail.com>
9
+
10
+ """
11
+
12
+ import operator
13
+ from typing import Callable
14
+
15
+ import numpy as np
16
+ import numpy.polynomial as poly
17
+ import scipy.fftpack as fftpack
18
+ import scipy.interpolate
19
+ from scipy import linalg
20
+ from typing_extensions import Self
21
+
22
+ from .polyfun import Polyfun, cast_scalar
23
+
24
+
25
+ class Chebfun(Polyfun):
26
+ """
27
+ Eventually set this up so that a Chebfun is a collection of Chebfuns. This
28
+ will enable piecewise smooth representations al la Matlab Chebfun v2.0.
29
+ """
30
+
31
+ # ----------------------------------------------------------------
32
+ # Standard construction class methods.
33
+ # ----------------------------------------------------------------
34
+
35
+ @classmethod
36
+ def identity(cls, domain=(-1.0, 1.0)) -> Self:
37
+ """
38
+ The identity function x -> x.
39
+ """
40
+ return cls.from_data([domain[1], domain[0]], domain)
41
+
42
+ @classmethod
43
+ def basis(cls, n: int) -> Self:
44
+ """
45
+ Chebyshev basis functions T_n.
46
+ """
47
+ if n == 0:
48
+ return cls(np.array([1.0]))
49
+ vals = np.ones(n + 1)
50
+ vals[1::2] = -1
51
+ return cls(vals)
52
+
53
+ # ----------------------------------------------------------------
54
+ # Integration and differentiation
55
+ # ----------------------------------------------------------------
56
+
57
+ def sum(self) -> complex:
58
+ """
59
+ Evaluate the integral over the given interval using
60
+ Clenshaw-Curtis quadrature.
61
+ """
62
+ ak = self.coefficients()
63
+ ak2 = ak[::2]
64
+ n = len(ak2)
65
+ Tints = 2 / (1 - (2 * np.arange(n)) ** 2)
66
+ val = np.sum((Tints * ak2.T).T, axis=0)
67
+ a_, b_ = self.domain
68
+ return 0.5 * (b_ - a_) * val
69
+
70
+ def integrate(self) -> Self:
71
+ """
72
+ Return the object representing the primitive of self over the domain. The
73
+ output starts at zero on the left-hand side of the domain.
74
+ """
75
+ coeffs = self.coefficients()
76
+ a, b = self.domain
77
+ int_coeffs = 0.5 * (b - a) * poly.chebyshev.chebint(coeffs)
78
+ antiderivative = self.from_coeff(int_coeffs, domain=self.domain)
79
+ return antiderivative.shift(-antiderivative(a))
80
+
81
+ def differentiate(self, n: int = 1) -> Self:
82
+ """
83
+ n-th derivative, default 1.
84
+ """
85
+ ak = self.coefficients()
86
+ a_, b_ = self.domain
87
+ for _ in range(n):
88
+ ak = self.differentiator(ak)
89
+ return self.from_coeff((2.0 / (b_ - a_)) ** n * ak, domain=self.domain)
90
+
91
+ # ----------------------------------------------------------------
92
+ # Roots
93
+ # ----------------------------------------------------------------
94
+ def roots(self) -> np.ndarray:
95
+ """
96
+ Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun
97
+ is recursively subsampled until it is successfully represented to
98
+ machine precision by a sequence of piecewise interpolants of degree
99
+ 100 or less. A colleague matrix eigenvalue solve is then applied to
100
+ each of these pieces and the results are concatenated.
101
+
102
+ See:
103
+ J. P. Boyd, Computing zeros on a real interval through Chebyshev
104
+ expansion and polynomial rootfinding, SIAM J. Numer. Anal., 40
105
+ (2002), pp. 1666-1682.
106
+ """
107
+ if self.size() == 1:
108
+ return np.array([])
109
+
110
+ elif self.size() <= 100:
111
+ ak = self.coefficients()
112
+ v = np.zeros_like(ak[:-1])
113
+ v[1] = 0.5
114
+ C1 = linalg.toeplitz(v)
115
+ C2 = np.zeros_like(C1)
116
+ C1[0, 1] = 1.0
117
+ C2[-1, :] = ak[:-1]
118
+ C = C1 - 0.5 / ak[-1] * C2
119
+ eigenvalues = linalg.eigvals(C)
120
+ roots = [eig.real for eig in eigenvalues if np.allclose(eig.imag, 0, atol=1e-10) and np.abs(eig.real) <= 1]
121
+ scaled_roots = self._ui_to_ab(np.array(roots))
122
+ return scaled_roots
123
+ else:
124
+ # divide at a close-to-zero split-point
125
+ split_point = self._ui_to_ab(0.0123456789)
126
+ return np.concatenate((
127
+ self.restrict((self.domain[0], split_point)).roots(),
128
+ self.restrict((split_point, self.domain[1])).roots(),
129
+ ))
130
+
131
+ # ----------------------------------------------------------------
132
+ # Interpolation and evaluation (go from values to coefficients)
133
+ # ----------------------------------------------------------------
134
+
135
+ @classmethod
136
+ def interpolation_points(cls, N: int) -> np.ndarray:
137
+ """
138
+ N Chebyshev points in [-1, 1], boundaries included
139
+ """
140
+ if N == 1:
141
+ return np.array([0.0])
142
+ return np.cos(np.arange(N) * np.pi / (N - 1))
143
+
144
+ @classmethod
145
+ def sample_function(cls, f: Callable, N: int) -> np.ndarray:
146
+ """
147
+ Sample a function on N+1 Chebyshev points.
148
+ """
149
+ x = cls.interpolation_points(N + 1)
150
+ try:
151
+ return f(x)
152
+ except ValueError: # needed when trying to sample functions which can't take a vector argument
153
+ return np.vectorize(f)(x)
154
+
155
+ @classmethod
156
+ def polyfit(cls, sampled: np.ndarray) -> np.ndarray:
157
+ """
158
+ Compute Chebyshev coefficients for values located on Chebyshev points.
159
+ sampled: array; first dimension is number of Chebyshev points
160
+ """
161
+ asampled = np.asarray(sampled)
162
+ if len(asampled) == 1:
163
+ return asampled
164
+ evened = even_data(asampled)
165
+ coeffs = dct(evened)
166
+ return coeffs
167
+
168
+ @classmethod
169
+ def polyval(cls, chebcoeff: np.ndarray) -> np.ndarray:
170
+ """
171
+ Compute the interpolation values at Chebyshev points.
172
+ chebcoeff: Chebyshev coefficients
173
+ """
174
+ N = len(chebcoeff)
175
+ if N == 1:
176
+ return chebcoeff
177
+
178
+ data = even_data(chebcoeff) / 2
179
+ data[0] *= 2
180
+ data[N - 1] *= 2
181
+
182
+ fftdata = 2 * (N - 1) * fftpack.ifft(data, axis=0)
183
+ complex_values = fftdata[:N]
184
+ # convert to real if input was real
185
+ values = np.real(complex_values) if np.isrealobj(chebcoeff) else complex_values
186
+ return values
187
+
188
+ @classmethod
189
+ def interpolator(cls, x: np.ndarray, values: np.ndarray) -> scipy.interpolate.BarycentricInterpolator:
190
+ """
191
+ Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x
192
+ """
193
+ # hacking the barycentric interpolator by computing the weights in advance
194
+ p = scipy.interpolate.BarycentricInterpolator([0.0, 1.0])
195
+ N = len(values)
196
+ weights = np.ones(N)
197
+ weights[0] = 0.5
198
+ weights[1::2] = -1
199
+ weights[-1] *= 0.5
200
+ p.wi = weights
201
+ p.xi = x
202
+ p.set_yi(values)
203
+ return p
204
+
205
+ # ----------------------------------------------------------------
206
+ # Helper for differentiation.
207
+ # ----------------------------------------------------------------
208
+
209
+ @classmethod
210
+ def differentiator(cls, A: np.ndarray) -> np.ndarray:
211
+ """Differentiate a set of Chebyshev polynomial expansion
212
+ coefficients
213
+ Originally from http://www.scientificpython.net/pyblog/chebyshev-differentiation
214
+ + (lots of) bug fixing + pythonisation
215
+ """
216
+ m = len(A)
217
+ SA = (A.T * 2 * np.arange(m)).T
218
+ DA = np.zeros_like(A)
219
+ if m == 1: # constant
220
+ return np.zeros_like(A[0:1])
221
+ if m == 2: # linear
222
+ return A[1:2,]
223
+ DA[m - 3 : m - 1,] = SA[m - 2 : m,]
224
+ for j in range(m // 2 - 1):
225
+ k = m - 3 - 2 * j
226
+ DA[k] = SA[k + 1] + DA[k + 2]
227
+ DA[k - 1] = SA[k] + DA[k + 1]
228
+ DA[0] = (SA[1] + DA[2]) * 0.5
229
+ return DA
230
+
231
+
232
+ # ----------------------------------------------------------------
233
+ # General utilities
234
+ # ----------------------------------------------------------------
235
+
236
+
237
+ def even_data(data: np.ndarray) -> np.ndarray:
238
+ """
239
+ Construct Extended Data Vector (equivalent to creating an
240
+ even extension of the original function)
241
+ Return: array of length 2(N-1)
242
+ For instance, [0,1,2,3,4] --> [0,1,2,3,4,3,2,1]
243
+ """
244
+ return np.concatenate(
245
+ [data, data[-2:0:-1]],
246
+ )
247
+
248
+
249
+ def dct(data: np.ndarray) -> np.ndarray:
250
+ """
251
+ Compute DCT using FFT
252
+ """
253
+ N = len(data) // 2
254
+ fftdata = fftpack.fft(data, axis=0)[: N + 1]
255
+ fftdata /= N
256
+ fftdata[0] /= 2.0
257
+ fftdata[-1] /= 2.0
258
+ data = np.real(fftdata) if np.isrealobj(data) else fftdata
259
+ return data
260
+
261
+
262
+ # ----------------------------------------------------------------
263
+ # Add overloaded operators
264
+ # ----------------------------------------------------------------
265
+
266
+
267
+ def _add_operator(cls, op):
268
+ def method(self, other):
269
+ if not self.same_domain(other):
270
+ raise self.DomainMismatch(self.domain, other.domain)
271
+ return self.from_function(
272
+ lambda x: op(self(x).T, other(x).T).T,
273
+ domain=self.domain,
274
+ )
275
+
276
+ cast_method = cast_scalar(method)
277
+ name = "__" + op.__name__ + "__"
278
+ cast_method.__name__ = name
279
+ cast_method.__doc__ = f"operator {name}"
280
+ setattr(cls, name, cast_method)
281
+
282
+
283
+ def rdiv(a, b):
284
+ return b / a
285
+
286
+
287
+ for _op in [operator.mul, operator.truediv, operator.pow, rdiv]:
288
+ _add_operator(Polyfun, _op)
289
+
290
+ # ----------------------------------------------------------------
291
+ # Add numpy ufunc delegates
292
+ # ----------------------------------------------------------------
293
+
294
+
295
+ def _add_delegate(ufunc):
296
+ def method(self):
297
+ return self.from_function(lambda x: ufunc(self(x)), domain=self.domain)
298
+
299
+ name = ufunc.__name__
300
+ method.__name__ = name
301
+ method.__doc__ = f"delegate for numpy's ufunc {name}"
302
+ setattr(Polyfun, name, method)
303
+
304
+
305
+ # Following list generated from:
306
+ # https://github.com/numpy/numpy/blob/master/numpy/core/code_generators/generate_umath.py
307
+ for func in [
308
+ np.arccos,
309
+ np.arccosh,
310
+ np.arcsin,
311
+ np.arcsinh,
312
+ np.arctan,
313
+ np.arctanh,
314
+ np.cos,
315
+ np.sin,
316
+ np.tan,
317
+ np.cosh,
318
+ np.sinh,
319
+ np.tanh,
320
+ np.exp,
321
+ np.exp2,
322
+ np.expm1,
323
+ np.log,
324
+ np.log2,
325
+ np.log1p,
326
+ np.sqrt,
327
+ np.fabs,
328
+ ]:
329
+ _add_delegate(func)
330
+
331
+
332
+ # ----------------------------------------------------------------
333
+ # General Aliases
334
+ # ----------------------------------------------------------------
335
+ ## chebpts = interpolation_points
@@ -0,0 +1,50 @@
1
+ from typing import Callable, Optional
2
+
3
+ import numpy as np
4
+
5
+ from .chebfun import Chebfun
6
+ from .polyfun import Polyfun
7
+
8
+ # ----------------------------------------------------------------
9
+ # Constructor inspired by the Matlab version
10
+ # ----------------------------------------------------------------
11
+
12
+
13
+ def chebfun(
14
+ f: Optional[Callable] = None,
15
+ domain: tuple = (-1, 1),
16
+ N: Optional[int] = None,
17
+ chebcoeff: Optional[np.ndarray] = None,
18
+ ):
19
+ """
20
+ Create a Chebyshev polynomial approximation of the function $f$ on the interval :math:`[-1, 1]`.
21
+
22
+ :param callable f: any univariate real numerical function
23
+ :param int N: (default = None) specify number of interpolating points
24
+ :param np.array chebcoeff: (default = np.array(0)) specify the coefficients
25
+ """
26
+
27
+ # Chebyshev coefficients
28
+ if chebcoeff is not None:
29
+ return Chebfun.from_coeff(chebcoeff, domain)
30
+
31
+ # another instance
32
+ if isinstance(f, Polyfun):
33
+ return Chebfun.from_fun(f)
34
+
35
+ # callable
36
+ if callable(f):
37
+ return Chebfun.from_function(f, domain, N)
38
+
39
+ # from here on, assume that f is None, or iterable
40
+ if np.isscalar(f):
41
+ f = [f]
42
+
43
+ try:
44
+ iter(f) # interpolation values provided
45
+ except TypeError:
46
+ pass
47
+ else:
48
+ return Chebfun(f, domain)
49
+
50
+ raise TypeError(f"Impossible to initialise the object from an object of type {type(f)}")