Commit 5ba0b66d authored by Martin Reinecke's avatar Martin Reinecke
Browse files

Merge branch 'NIFTy_5' into docs_lp

parents 86945e26 3755c48d
NIFTy - Numerical Information Field Theory
==========================================
[![build status](https://gitlab.mpcdf.mpg.de/ift/nifty-dev/badges/NIFTy_5/build.svg)](https://gitlab.mpcdf.mpg.de/ift/nifty-dev/commits/NIFTy_5)
[![coverage report](https://gitlab.mpcdf.mpg.de/ift/nifty-dev/badges/NIFTy_5/coverage.svg)](https://gitlab.mpcdf.mpg.de/ift/nifty-dev/commits/NIFTy_5)
[![build status](https://gitlab.mpcdf.mpg.de/ift/NIFTy/badges/NIFTy_5/build.svg)](https://gitlab.mpcdf.mpg.de/ift/NIFTy/commits/NIFTy_5)
[![coverage report](https://gitlab.mpcdf.mpg.de/ift/NIFTy/badges/NIFTy_5/coverage.svg)](https://gitlab.mpcdf.mpg.de/ift/NIFTy/commits/NIFTy_5)
**NIFTy** project homepage:
[http://ift.pages.mpcdf.de/NIFTy](http://ift.pages.mpcdf.de/NIFTy)
......@@ -66,14 +66,15 @@ NIFTy5 and its mandatory dependencies can be installed via:
Plotting support is added via:
pip3 install --user matplotlib
sudo apt-get install python3-matplotlib
FFTW support is added via:
NIFTy uses Numpy's FFT implementation by default. For large problems FFTW may be
used because of its higher performance. It can be installed via:
sudo apt-get install libfftw3-dev
pip3 install --user pyfftw
To actually use FFTW in your Nifty calculations, you need to call
To enable FFTW usage in NIFTy, call
nifty5.fft.enable_fftw()
......@@ -90,14 +91,13 @@ Support for spherical harmonic transforms is added via:
MPI support is added via:
sudo apt-get install openmpi-bin libopenmpi-dev
pip3 install --user mpi4py
sudo apt-get install python3-mpi4py
### Running the tests
To run the tests, additional packages are required:
sudo apt-get install python3-coverage python3-pytest python3-pytest-cov
sudo apt-get install python3-pytest-cov
Afterwards the tests (including a coverage report) can be run using the
following command in the repository root:
......
......@@ -12,7 +12,7 @@ NIFTy5 and its mandatory dependencies can be installed via::
Plotting support is added via::
pip3 install --user matplotlib
sudo apt-get install python3-matplotlib
NIFTy uses Numpy's FFT implementation by default. For large problems FFTW may be
used because of its higher performance. It can be installed via::
......@@ -37,5 +37,4 @@ Support for spherical harmonic transforms is added via::
MPI support is added via::
sudo apt-get install openmpi-bin libopenmpi-dev
pip3 install --user mpi4py
sudo apt-get install python3-mpi4py
......@@ -34,8 +34,8 @@ Discretisation and index notation
.................................
To compute anything numerically, we first need to represent the problem in finite dimensions.
As for stochastic processes, several discretisations of :math:`\mathcal{S}` like collocation methods, expansion into orthogonal polynomials, etc. can be used (see [6]_, [7]_ for an overview and further information about their reliability).
In particular, NIFTy uses the midpoint method as reviewed in section 2.1 in [6]_ and Fourier expansion.
As for stochastic processes, several discretisations of :math:`\mathcal{S}` like collocation methods, expansion into orthogonal polynomials, etc. can be used (see [1]_, [2]_ for an overview and further information about their reliability).
In particular, NIFTy uses the midpoint method as reviewed in section 2.1 of [1]_ and Fourier expansion.
Without going into the details, discretisation methods basically introduce a finite set of basis functions :math:`\{\phi_i\}_{i\in \mathcal{I}}`, where :math:`\mathcal{I}` denotes a generic index set with :math:`|\mathcal{I}| = N` being the chosen discretisation dimension.
Any Riemannian manifold :math:`(\mathcal{M},g)` is equipped with a canonical scalar product given by
......@@ -70,7 +70,7 @@ After projection, any function :math:`f \in \mathcal{S}` is represented by its a
which defines an embedding :math:`\hat{\mathcal{S}} \hookrightarrow \mathcal{S} = \mathcal{F}(\mathcal{M})`.
**Changes of bases** are performed by reapproximating the :math:`\{\phi_i\}_{i\in \mathcal{I}}` in terms of another basis :math:`\{\phi'_i\}_{i\in \mathcal{I'}}` :
**Changes of base** are performed by reapproximating the :math:`\{\phi_i\}_{i\in \mathcal{I}}` in terms of another basis :math:`\{\phi'_i\}_{i\in \mathcal{I'}}`:
.. math::
......@@ -81,7 +81,7 @@ The latter is e.g. true for regular collocation grids on tori and the associated
The discrete Fourier transform then maps between those bases without loss of information.
**Discretisation of operators** works in the same way by expansion.
For illustration purposes, let :math:`A: \mathcal{S} \rightarrow \mathcal{S}` be a not necessarily linear operator.
For illustration purposes, let :math:`A: \mathcal{S} \rightarrow \mathcal{S}` be a (not necessarily linear) operator.
The result of its action on functions :math:`s` is known and may be expanded in :math:`\{\phi_i\}_{i\in \mathcal{I}}`, i.e.
.. math::
......@@ -94,14 +94,14 @@ Integrals can now be written as
\left< s , A[t] \right>_{\mathcal{M}} \approx s^i \left< \phi_i , \phi_j \right>_{\mathcal{M}} (A[t])^j \equiv s^i \, v_{ij} \, (A[t])^j \, ,
where the appearence of the volume metric can be hidden by lowering the first index of the operator,
where the appearance of the volume metric can be hidden by lowering the first index of the operator,
.. math::
(A[w])_k := v_{km} \, (A[w])^m \, .
Hence, the volume metric needs not to be carried along if the operators are defined in this fashion right from the start.
Linear operators mapping several functions to another function are completly specified by their action on a given basis, and we define
Hence, the volume metric need not be carried along if the operators are defined in this fashion right from the start.
Linear operators mapping several functions to another function are completely specified by their action on a given basis, and we define
.. math::
......@@ -115,8 +115,8 @@ If :math:`A` is a (linear) integral operator defined by a kernel :math:`\tilde{A
&= v^{km} \, \left< \phi_m, A[\phi_i,\phi_j,\ldots] \right>_{\mathcal{M}} \\
&= v^{km} \, \int_{\mathcal{M}} \mathrm{d} x\,\sqrt{|g|}\,\left(\prod_{n}^{|\{ij\ldots\}|}\int_{\mathcal{M}} \mathrm{d} y_n \, \sqrt{|g|}\right) \,\,\phi_m(x)\, \tilde{A}(x,y_1,y_2,\ldots)\, \phi_i(y_1) \, \phi_j(y_2) \cdots \, .
.. [6] Bruno Sudret and Armen Der Kiureghian (2000), "Stochastic Finite Element Methods and Reliability: A State-of-the-Art Report"
.. [7] Dongbin Xiu (2010), "Numerical methods for stochastic computations", Princeton University Press.
.. [1] Bruno Sudret and Armen Der Kiureghian (2000), "Stochastic Finite Element Methods and Reliability: A State-of-the-Art Report"
.. [2] Dongbin Xiu (2010), "Numerical methods for stochastic computations", Princeton University Press.
Resolution and self-consistency
...............................
......@@ -129,40 +129,40 @@ Apparently, the discretisation and the discretised response need to satisfy a se
.. math::
R = \hat{R} \circ D \, .
An obvious corrollary is that different discretisations :math:`D, D'` with resulting discretised responses :math:`\hat{R}, \hat{R}'` will need to satisfy
An obvious corollary is that different discretisations :math:`D, D'` with resulting discretised responses :math:`\hat{R}, \hat{R}'` will need to satisfy
.. math::
\hat{R} \circ D = \hat{R}' \circ D' \, .
NIFTy is implemented such that in order to change resolution, only the line of code defining the space needs to be altered.
It automatically takes care of depended structures like volume factors, discretised operators and responses.
A visualisation of this can be seen in figure 2 and 3, which displays the MAP inference of a signal at various resolutions.
It automatically takes care of dependent structures like volume factors, discretised operators and responses.
A visualisation of this can be seen in figure 2, which displays the MAP inference of a signal at various resolutions.
.. figure:: images/converging_discretization.png
:scale: 80%
:align: center
Figure 3: Inference result converging at high resolution.
Figure 2: Inference result converging at high resolution.
Implementation in NIFTy
-----------------------
.......................
.. currentmodule:: nifty5
Most codes in NIFTy will contain the description of a measurement process,
or more generally, a log-likelihood.
Most codes in NIFTy will contain the description of a measurement process or,
more generally, a log-likelihood.
This log-likelihood is necessarily a map from the quantity of interest (a field) to a real number.
The likelihood has to be unitless because it is a log-probability and should not scale with resolution.
Often, likelihoods contain integrals over the quantity of interest :math:`s`, which have to be discretized, e.g. by a sum
The log-likelihood has to be unitless because it is a log-probability and should not scale with resolution.
Often, log-likelihoods contain integrals over the quantity of interest :math:`s`, which have to be discretized, e.g. by a sum
.. math::
\int_\Omega \text{d}x\, s(x) \approx \sum_i s_i\int_{\Omega_i}\text{d}x\, 1
\int_\Omega \text{d}x\, s(x) \approx \sum_i s^i\int_{\Omega_i}\text{d}x\, 1
Here the domain of the integral :math:`\Omega = \dot{\bigcup_q} \; \Omega_i` is the disjoint union over smaller :math:`\Omega_i`, e.g. the pixels of the space, and :math:`s_i` is the discretized field value on the :math:`i`-th pixel.
This introduces the weighting :math:`V_i=\int_{\Omega_i}\text{d}x\, 1`, also called the volume factor, a property of the space.
NIFTy aids you in constructing your own likelihood by providing methods like :func:`~field.Field.weight`, which weights all pixels of a field with its corresponding volume.
NIFTy aids you in constructing your own log-likelihood by providing methods like :func:`~field.Field.weight`, which weights all pixels of a field with their corresponding volume.
An integral over a :class:`~field.Field` :code:`s` can be performed by calling :code:`s.weight(1).sum()`, which is equivalent to :code:`s.integrate()`.
Volume factors are also applied automatically in the following places:
......@@ -170,32 +170,38 @@ Volume factors are also applied automatically in the following places:
- some response operators, such as the :class:`~library.los_response.LOSResponse`. In this operator a line integral is descritized, so a 1-dimensional volume factor is applied.
- In :class:`~library.correlated_fields.CorrelatedField` as well :class:`~library.correlated_fields.MfCorrelatedField`, the field is multiplied by the square root of the total volume in configuration space. This ensures that the same field reconstructed over a larger domain has the same variance in position space in the limit of infinite resolution. It also ensures that power spectra in NIFTy behave according to the definition of a power spectrum, namely the power of a k-mode is the expectation of the k-mode square, divided by the volume of the space.
Note that in contrast to some older versions of NIFTy, the dot product of fields does not apply a volume factor
Note that in contrast to some older versions of NIFTy, the dot product :code:`s.vdot(t)` of fields does **not** apply a volume factor, but instead just sums over the field components,
.. math::
s^\dagger t = \sum_i s_i^* t_i .
s^\dagger t = \sum_i \overline{s^i}\, t^i \, ,
If this dot product is supposed to be invariant under changes in resolution, then either :math:`s_i` or :math:`t_i` has to decrease as the number of pixels increases, or more specifically, one of the two fields has to be an extensive quantity while the other has to be intensive.
One can make this more explicit by denoting intensive quantities with upper index and extensive quantities with lower index
where the bar denotes complex conjugation.
This dot product is **not** invariant under changes in resolution, as then the number of discretised field components increases.
Upper index components like :math:`s^i`, however, are designed **not** to scale with the volume.
One solution to obtain a resolution independent quantity is to make one of the two factors extensive while the other stays intensive.
This is more explicit when intensive quantities are denoted by an upper index and extensive quantities by a lower index,
.. math::
s^\dagger t = (s^*)^i t_i
s^\dagger t = \overline{s^i} t_i
where we used Einstein sum convention.
This notation connects to the theoretical discussion before.
One of the field has to have the volume metric already incorperated to assure the continouum limit works.
Here, the volume metric is incorporated by lowering one index, i.e. :math:`t_i = v_{ij}\,t^j`.
When building statistical models, all indices will end up matching this upper-lower convention automatically, e.g. for a Gaussian log-likelihood :math:`L` we have
.. math::
L = \frac{1}{2}s^i \left(S^{-1}\right)_{ij} s^j
L = \frac{1}{2}\overline{s^i} \left(S^{-1}\right)_{ij} s^j
with
with the covariance defined by
.. math::
\left(S^{-1}\right)_{ij} = \left(S^{kl}\right)_ij^{-1} = \left(\left<(s^*)^ks^l\right>\right)^{-1})_{ij}\ .
S^{ij} = \left<s^i\overline{s^j}\right>\ .
Thus the covariance matrix :math:`S` will ensure that the whole likelihood expression does not scale with resolution.
**This upper-lower index convention is not coded into NIFTy**, in order to not reduce user freedom.
One should however have this in mind when constructing algorithms in order to ensure resolution independence.
Consequently, the inverse covariance operator will automatically have lower indices,
Note that while the upper-lower index convention ensures resolution independence, this does not automatically fix the pixilization.
.. math::
\left(S^{-1}\right)_{ij} S^{jk} = \delta^{\,\,k}_j\ ,
ensuring that the whole log-likelihood expression does not scale with resolution.
**This upper-lower index convention is not coded into NIFTy**, in order to not reduce user freedom.
One should however have this in mind when constructing log-likelihoods in order to ensure resolution independence.
......@@ -133,7 +133,7 @@ class GradientNormController(IterationController):
if self._iteration_limit is not None:
if self._itcount >= self._iteration_limit:
logger.warning(
"{} Iteration limit reached. Assuming convergence"
"{}Iteration limit reached. Assuming convergence"
.format("" if self._name is None else self._name+": "))
return self.CONVERGED
if self._ccount >= self._convergence_level:
......
......@@ -15,62 +15,79 @@
#
# NIFTy is being developed at the Max-Planck-Institut fuer Astrophysik.
from .energy import Energy
from ..linearization import Linearization
from .. import utilities
from ..linearization import Linearization
from ..operators.energy_operators import StandardHamiltonian
from .energy import Energy
class MetricGaussianKL(Energy):
"""Provides the sampled Kullback-Leibler divergence between a distribution
and a Metric Gaussian.
A Metric Gaussian is used to approximate some other distribution.
It is a Gaussian distribution that uses the Fisher Information Metric
of the other distribution at the location of its mean to approximate the
variance. In order to infer the mean, the a stochastic estimate of the
A Metric Gaussian is used to approximate another probability distribution.
It is a Gaussian distribution that uses the Fisher information metric of
the other distribution at the location of its mean to approximate the
variance. In order to infer the mean, a stochastic estimate of the
Kullback-Leibler divergence is minimized. This estimate is obtained by
drawing samples from the Metric Gaussian at the current mean.
During minimization these samples are kept constant, updating only the
mean. Due to the typically nonlinear structure of the true distribution
these samples have to be updated by re-initializing this class at some
point. Here standard parametrization of the true distribution is assumed.
sampling the Metric Gaussian at the current mean. During minimization
these samples are kept constant; only the mean is updated. Due to the
typically nonlinear structure of the true distribution these samples have
to be updated eventually by intantiating `MetricGaussianKL` again. For the
true probability distribution the standard parametrization is assumed.
Parameters
----------
mean : Field
The current mean of the Gaussian.
Mean of the Gaussian probability distribution.
hamiltonian : StandardHamiltonian
The StandardHamiltonian of the approximated probability distribution.
Hamiltonian of the approximated probability distribution.
n_samples : integer
The number of samples used to stochastically estimate the KL.
Number of samples used to stochastically estimate the KL.
constants : list
A list of parameter keys that are kept constant during optimization.
List of parameter keys that are kept constant during optimization.
Default is no constants.
point_estimates : list
A list of parameter keys for which no samples are drawn, but that are
optimized for, corresponding to point estimates of these.
List of parameter keys for which no samples are drawn, but that are
(possibly) optimized for, corresponding to point estimates of these.
Default is to draw samples for the complete domain.
mirror_samples : boolean
Whether the negative of the drawn samples are also used,
as they are equaly legitimate samples. If true, the number of used
as they are equally legitimate samples. If true, the number of used
samples doubles. Mirroring samples stabilizes the KL estimate as
extreme sample variation is counterbalanced. (default : False)
Notes
-----
For further details see: Metric Gaussian Variational Inference
(FIXME in preparation)
extreme sample variation is counterbalanced. Default is False.
_samples : None
Only a parameter for internal uses. Typically not to be set by users.
Note
----
The two lists `constants` and `point_estimates` are independent from each
other. It is possible to sample along domains which are kept constant
during minimization and vice versa.
See also
--------
Metric Gaussian Variational Inference (FIXME in preparation)
"""
def __init__(self, mean, hamiltonian, n_samples, constants=[],
point_estimates=None, mirror_samples=False,
point_estimates=[], mirror_samples=False,
_samples=None):
super(MetricGaussianKL, self).__init__(mean)
if not isinstance(hamiltonian, StandardHamiltonian):
raise TypeError
if hamiltonian.domain is not mean.domain:
raise ValueError
if not isinstance(n_samples, int):
raise TypeError
self._constants = list(constants)
self._point_estimates = list(point_estimates)
if not isinstance(mirror_samples, bool):
raise TypeError
self._hamiltonian = hamiltonian
self._constants = constants
if point_estimates is None:
point_estimates = constants
self._constants_samples = point_estimates
if _samples is None:
met = hamiltonian(Linearization.make_partial_var(
mean, point_estimates, True)).metric
......@@ -96,7 +113,7 @@ class MetricGaussianKL(Energy):
def at(self, position):
return MetricGaussianKL(position, self._hamiltonian, 0,
self._constants, self._constants_samples,
self._constants, self._point_estimates,
_samples=self._samples)
@property
......
......@@ -261,7 +261,6 @@ class BernoulliEnergy(EnergyOperator):
"""
def __init__(self, d):
print(d.dtype)
if not isinstance(d, Field) or not np.issubdtype(d.dtype, np.integer):
raise TypeError
if not np.all(np.logical_or(d.local_data == 0, d.local_data == 1)):
......
......@@ -26,7 +26,7 @@ from .linear_operator import LinearOperator
class RegriddingOperator(LinearOperator):
"""Linearly interpolates a RGSpace to an RGSpace with coarser resolution.
"""Linearly interpolates an RGSpace to an RGSpace with coarser resolution.
Parameters
----------
......@@ -47,7 +47,6 @@ class RegriddingOperator(LinearOperator):
if not isinstance(dom, RGSpace):
raise TypeError("RGSpace required")
if len(new_shape) != len(dom.shape):
print(new_shape, dom.shape)
raise ValueError("Shape mismatch")
if any([a > b for a, b in zip(new_shape, dom.shape)]):
raise ValueError("New shape must not be larger than old shape")
......
......@@ -55,6 +55,115 @@ def _mollweide_helper(xsize):
return res, mask, theta, phi
def _rgb_data(spectral_cube):
_xyz = np.array(
[[0.000160, 0.000662, 0.002362, 0.007242, 0.019110,
0.043400, 0.084736, 0.140638, 0.204492, 0.264737,
0.314679, 0.357719, 0.383734, 0.386726, 0.370702,
0.342957, 0.302273, 0.254085, 0.195618, 0.132349,
0.080507, 0.041072, 0.016172, 0.005132, 0.003816,
0.015444, 0.037465, 0.071358, 0.117749, 0.172953,
0.236491, 0.304213, 0.376772, 0.451584, 0.529826,
0.616053, 0.705224, 0.793832, 0.878655, 0.951162,
1.014160, 1.074300, 1.118520, 1.134300, 1.123990,
1.089100, 1.030480, 0.950740, 0.856297, 0.754930,
0.647467, 0.535110, 0.431567, 0.343690, 0.268329,
0.204300, 0.152568, 0.112210, 0.081261, 0.057930,
0.040851, 0.028623, 0.019941, 0.013842, 0.009577,
0.006605, 0.004553, 0.003145, 0.002175, 0.001506,
0.001045, 0.000727, 0.000508, 0.000356, 0.000251,
0.000178, 0.000126, 0.000090, 0.000065, 0.000046,
0.000033],
[0.000017, 0.000072, 0.000253, 0.000769, 0.002004,
0.004509, 0.008756, 0.014456, 0.021391, 0.029497,
0.038676, 0.049602, 0.062077, 0.074704, 0.089456,
0.106256, 0.128201, 0.152761, 0.185190, 0.219940,
0.253589, 0.297665, 0.339133, 0.395379, 0.460777,
0.531360, 0.606741, 0.685660, 0.761757, 0.823330,
0.875211, 0.923810, 0.961988, 0.982200, 0.991761,
0.999110, 0.997340, 0.982380, 0.955552, 0.915175,
0.868934, 0.825623, 0.777405, 0.720353, 0.658341,
0.593878, 0.527963, 0.461834, 0.398057, 0.339554,
0.283493, 0.228254, 0.179828, 0.140211, 0.107633,
0.081187, 0.060281, 0.044096, 0.031800, 0.022602,
0.015905, 0.011130, 0.007749, 0.005375, 0.003718,
0.002565, 0.001768, 0.001222, 0.000846, 0.000586,
0.000407, 0.000284, 0.000199, 0.000140, 0.000098,
0.000070, 0.000050, 0.000036, 0.000025, 0.000018,
0.000013],
[0.000705, 0.002928, 0.010482, 0.032344, 0.086011,
0.197120, 0.389366, 0.656760, 0.972542, 1.282500,
1.553480, 1.798500, 1.967280, 2.027300, 1.994800,
1.900700, 1.745370, 1.554900, 1.317560, 1.030200,
0.772125, 0.570060, 0.415254, 0.302356, 0.218502,
0.159249, 0.112044, 0.082248, 0.060709, 0.043050,
0.030451, 0.020584, 0.013676, 0.007918, 0.003988,
0.001091, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000]])
MATRIX_SRGB_D65 = np.array(
[[3.2404542, -1.5371385, -0.4985314],
[-0.9692660, 1.8760108, 0.0415560],
[0.0556434, -0.2040259, 1.0572252]])
def _gammacorr(inp):
mask = np.zeros(inp.shape, dtype=np.float64)
mask[inp <= 0.0031308] = 1.
r1 = 12.92*inp
a = 0.055
r2 = (1 + a) * (np.maximum(inp, 0.0031308) ** (1/2.4)) - a
return r1*mask + r2*(1.-mask)
def lambda2xyz(lam):
lammin = 380.
lammax = 780.
lam = np.asarray(lam, dtype=np.float64)
lam = np.clip(lam, lammin, lammax)
idx = (lam-lammin)/(lammax-lammin)*(_xyz.shape[1]-1)
ii = np.maximum(0, np.minimum(79, int(idx)))
w1 = 1.-(idx-ii)
w2 = 1.-w1
c = w1*_xyz[:, ii] + w2*_xyz[:, ii+1]
return c
def getxyz(n):
E0, E1 = 1./700., 1./400.
E = E0 + np.arange(n)*(E1-E0)/(n-1)
res = np.zeros((3, n), dtype=np.float64)
for i in range(n):
res[:, i] = lambda2xyz(1./E[i])
return res
def to_logscale(arr, lo, hi):
res = arr.clip(lo, hi)
res = np.log(res/hi)
tmp = np.log(hi/lo)
res += tmp
res /= tmp
return res
spectral_cube = spectral_cube.reshape((-1, spectral_cube.shape[-1]))
xyz = getxyz(spectral_cube.shape[-1])
xyz_data = np.tensordot(spectral_cube, xyz, axes=[-1, -1])
xyz_data /= xyz_data.max()
xyz_data = to_logscale(xyz_data, max(1e-3, xyz_data.min()), 1.)
rgb_data = xyz_data.copy()
it = np.nditer(xyz_data[:, 0], flags=['multi_index'])
for x in range(xyz_data.shape[0]):
rgb_data[x] = _gammacorr(np.matmul(MATRIX_SRGB_D65, xyz_data[x]))
rgb_data = rgb_data.clip(0., 1.)
return rgb_data.reshape(spectral_cube.shape[:-1]+(-1,))
def _find_closest(A, target):
# A must be sorted
idx = np.clip(A.searchsorted(target), 1, len(A)-1)
......@@ -229,8 +338,16 @@ def _plot2D(f, ax, **kwargs):
dom = f.domain
if len(dom) > 1:
raise ValueError("DomainTuple must have exactly one entry.")
if len(dom) > 2:
raise ValueError("DomainTuple can have at most two entries.")
# check for multifrequency plotting
have_rgb = False
if len(dom) == 2:
if (not isinstance(dom[1], RGSpace)) or len(dom[1].shape) != 1:
raise TypeError("need 1D RGSpace as second domain")
rgb = _rgb_data(f.to_global_data())
have_rgb = True
label = kwargs.pop("label", None)
......@@ -243,39 +360,58 @@ def _plot2D(f, ax, **kwargs):
ax.set_xlabel(kwargs.pop("xlabel", ""))
ax.set_ylabel(kwargs.pop("ylabel", ""))
dom = dom[0]
cmap = kwargs.pop("colormap", plt.rcParams['image.cmap'])
if not have_rgb:
cmap = kwargs.pop("colormap", plt.rcParams['image.cmap'])
if isinstance(dom, RGSpace):
nx, ny = dom.shape
dx, dy = dom.distances
im = ax.imshow(
f.to_global_data().T, extent=[0, nx*dx, 0, ny*dy],
vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
cmap=cmap, origin="lower", **norm, **aspect)
plt.colorbar(im)
if have_rgb:
im = ax.imshow(
rgb, extent=[0, nx*dx, 0, ny*dy], origin="lower", **norm,
**aspect)
else:
im = ax.imshow(
f.to_global_data().T, extent=[0, nx*dx, 0, ny*dy],
vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
cmap=cmap, origin="lower", **norm, **aspect)
plt.colorbar(im)
_limit_xy(**kwargs)
return
elif isinstance(dom, (HPSpace, GLSpace)):
import pyHealpix
xsize = 800
res, mask, theta, phi = _mollweide_helper(xsize)
if have_rgb:
res = np.full(shape=res.shape+(3,), fill_value=1.,
dtype=np.float64)
if isinstance(dom, HPSpace):
ptg = np.empty((phi.size, 2), dtype=np.float64)
ptg[:, 0] = theta
ptg[:, 1] = phi
base = pyHealpix.Healpix_Base(int(np.sqrt(dom.size//12)), "RING")
res[mask] = f.to_global_data()[base.ang2pix(ptg)]
if have_rgb:
res[mask] = rgb[base.ang2pix(ptg)]
else:
res[mask] = f.to_global_data()[base.ang2pix(ptg)]
else:
ra = np.linspace(0, 2*np.pi, dom.nlon+1)
dec = pyHealpix.GL_thetas(dom.nlat)
ilat = _find_closest(dec, theta)
ilon = _find_closest(ra, phi)
ilon = np.where(ilon == dom.nlon, 0, ilon)
res[mask] = f.to_global_data()[ilat*dom.nlon + ilon]
if have_rgb:
res[mask] = rgb[ilat*dom[0].nlon + ilon]
else:
res[mask] = f.to_global_data()[ilat*dom.nlon + ilon]
plt.axis('off')
plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
cmap=cmap, origin="lower")
plt.colorbar(orientation="horizontal")
if have_rgb:
plt.imshow(res, origin="lower")
else:
plt.imshow(res, vmin=kwargs.get("zmin"), vmax=kwargs.get("zmax"),
cmap=cmap, origin="lower")
plt.colorbar(orientation="horizontal")
return
raise ValueError("Field type not(yet) supported")
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment