code.rst 17.8 KB
Newer Older
Philipp Arras's avatar
Philipp Arras committed
1
.. currentmodule:: nifty5
2

Martin Reinecke's avatar
Martin Reinecke committed
3
=============
4 5
Code Overview
=============
6

Martin Reinecke's avatar
Martin Reinecke committed
7 8 9 10

Executive summary
=================

11 12
The fundamental building blocks required for IFT computations are best
recognized from a large distance, ignoring all technical details.
13

14 15
From such a perspective,

Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
16
- IFT problems largely consist of the combination of several high dimensional
17
  *minimization* problems.
Philipp Arras's avatar
Philipp Arras committed
18
- Within NIFTy, *operators* are used to define the characteristic equations and
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
19
  properties of the problems.
Martin Reinecke's avatar
Martin Reinecke committed
20 21
- The equations are built mostly from the application of *linear operators*,
  but there may also be nonlinear functions involved.
22
- The unknowns in the equations represent either continuous physical *fields*,
Martin Reinecke's avatar
Martin Reinecke committed
23 24 25 26
  or they are simply individual measured *data points*.
- Discretized *fields* have geometrical information (like locations and volume
  elements) associated with every entry; this information is called the field's
  *domain*.
27 28 29 30 31 32 33 34 35 36 37 38 39

In the following sections, the concepts briefly presented here will be
discussed in more detail; this is done in reversed order of their introduction,
to avoid forward references.


Domains
=======


Abstract base class
-------------------

Philipp Arras's avatar
Philipp Arras committed
40
One of the fundamental building blocks of the NIFTy5 framework is the *domain*.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
Its required capabilities are expressed by the abstract :class:`Domain` class.
A domain must be able to answer the following queries:

- its total number of data entries (pixels), which is accessible via the
  :attr:`~Domain.size` property
- the shape of the array that is supposed to hold these data entries
  (obtainable by means of the :attr:`~Domain.shape` property)
- equality comparison to another :class:`Domain` instance


Unstructured domains
--------------------

Domains can be either *structured* (i.e. there is geometrical information
associated with them, like position in space and volume factors),
or *unstructured* (meaning that the data points have no associated manifold).

Unstructured domains can be described by instances of NIFTy's
:class:`UnstructuredDomain` class.


Structured domains
------------------

In contrast to unstructured domains, these domains have an assigned geometry.
NIFTy requires them to provide the volume elements of their grid cells.
The additional methods are specified in the abstract class
:class:`StructuredDomain`:

Martin Reinecke's avatar
Martin Reinecke committed
70
- The properties :attr:`~StructuredDomain.scalar_dvol`,
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  :attr:`~StructuredDomain.dvol`, and  :attr:`~StructuredDomain.total_volume`
  provide information about the domain's pixel volume(s) and its total volume.
- The property :attr:`~StructuredDomain.harmonic` specifies whether a domain
  is harmonic (i.e. describes a frequency space) or not
- Iff the domain is harmonic, the methods
  :meth:`~StructuredDomain.get_k_length_array`,
  :meth:`~StructuredDomain.get_unique_k_lengths`, and
  :meth:`~StructuredDomain.get_fft_smoothing_kernel_function` provide absolute
  distances of the individual grid cells from the origin and assist with
  Gaussian convolution.

NIFTy comes with several concrete subclasses of :class:`StructuredDomain`:

- :class:`RGSpace` represents a regular Cartesian grid with an arbitrary
  number of dimensions, which is supposed to be periodic in each dimension.
- :class:`HPSpace` and :class:`GLSpace` describe pixelisations of the
  2-sphere; their counterpart in harmonic space is :class:`LMSpace`, which
  contains spherical harmonic coefficients.
- :class:`PowerSpace` is used to describe one-dimensional power spectra.

Among these, :class:`RGSpace` can be harmonic or not (depending on constructor arguments), :class:`GLSpace`, :class:`HPSpace`, and :class:`PowerSpace` are
pure position domains (i.e. nonharmonic), and :class:`LMSpace` is always
harmonic.


Combinations of domains
=======================

The fundamental classes described above are often sufficient to specify the
100 101
domain of a field. In some cases, however, it will be necessary to define the
field on a product of elementary domains instead of a single one.
Philipp Arras's avatar
Philipp Arras committed
102
More sophisticated operators also require a set of several such fields.
103 104 105 106 107
Some examples are:

- sky emission depending on location and energy. This could be represented by
  a product of an :class:`HPSpace` (for location) with an :class:`RGSpace`
  (for energy).
Philipp Arras's avatar
Philipp Arras committed
108
- a polarized field, which could be modeled as a product of any structured
Martin Reinecke's avatar
Martin Reinecke committed
109 110
  domain (representing location) with a four-element
  :class:`UnstructuredDomain` holding Stokes I, Q, U and V components.
Martin Reinecke's avatar
Martin Reinecke committed
111 112 113
- a model for the sky emission, which holds both the current realization
  (on a harmonic domain) and a few inferred model parameters (e.g. on an
  unstructured grid).
114 115 116 117 118 119

Consequently, NIFTy defines a class called :class:`DomainTuple` holding
a sequence of :class:`Domain` objects, which is used to specify full field
domains. In principle, a :class:`DomainTuple` can even be empty, which implies
that the field living on it is a scalar.

Martin Reinecke's avatar
Martin Reinecke committed
120 121 122 123
A :class:`DomainTuple` supports iteration and indexing, and also provides the
properties :attr:`~DomainTuple.shape`, :attr:`~DomainTuple.size` in analogy to
the elementary :class:`Domain`.

Torsten Ensslin's avatar
Torsten Ensslin committed
124
An aggregation of several :class:`DomainTuple` s, each member identified by a
Martin Reinecke's avatar
Martin Reinecke committed
125
name, is described by the :class:`MultiDomain` class.
126 127 128 129

Fields
======

Martin Reinecke's avatar
Martin Reinecke committed
130 131 132
Fields on a single DomainTuple
------------------------------

133 134 135 136 137 138
A :class:`Field` object consists of the following components:

- a domain in form of a :class:`DomainTuple` object
- a data type (e.g. numpy.float64)
- an array containing the actual values

Martin Reinecke's avatar
Martin Reinecke committed
139
Usually, the array is stored in the form of a ``numpy.ndarray``, but for very
Martin Reinecke's avatar
Martin Reinecke committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153
resource-intensive tasks NIFTy also provides an alternative storage method to
be used with distributed memory processing.

Fields support a wide range of arithmetic operations, either involving two
fields with equal domains, or a field and a scalar.
Contractions (like summation, integration, minimum/maximum, computation of
statistical moments) can be carried out either over an entire field (producing
a scalar result) or over sub-domains (resulting in a field living on a smaller
domain). Scalar products of two fields can also be computed easily.

There is also a set of convenience functions to generate fields with constant
values or fields filled with random numbers according to a user-specified
distribution.

Martin Reinecke's avatar
Martin Reinecke committed
154 155 156 157 158
Like almost all NIFTy objects, fields are immutable: their value or any other
attribute cannot be modified after construction. To manipulate a field in ways
that are not covered by the provided standard operations, its data content must
be extracted first, then changed, and a new field has to be created from the
result.
Martin Reinecke's avatar
Martin Reinecke committed
159

160
Fields defined on a MultiDomain
Martin Reinecke's avatar
Martin Reinecke committed
161 162 163
------------------------------

The :class:`MultiField` class can be seen as a dictionary of individual
164
:class:`Field` s, each identified by a name, which is defined on a
Martin Reinecke's avatar
Martin Reinecke committed
165 166 167 168 169 170 171 172
:class:`MultiDomain`.


Operators
=========

All transformations between different NIFTy fields are expressed  (explicitly
or implicitly) in the form of :class:`Operator` objects. The interface of this
Torsten Ensslin's avatar
Torsten Ensslin committed
173
class is very minimalistic: it has a property called :class:`domain` which returns
174
a :class:`DomainTuple` or :class:`MultiDomain` object specifying the structure of the
Torsten Ensslin's avatar
Torsten Ensslin committed
175
:class:`Field` s or :class:`MultiField` s it expects as input, another property :class:`target`
Martin Reinecke's avatar
Martin Reinecke committed
176 177 178
describing its output, and finally an overloaded `apply` method, which can
take

Torsten Ensslin's avatar
Torsten Ensslin committed
179 180 181 182
- a :class:`Field`/:class:`MultiField`object, in which case it returns the transformed
  :class:`Field`/:class:`MultiField`
- a :class:`Linearization` object, in which case it returns the transformed
  :class:`Linearization`
Martin Reinecke's avatar
Martin Reinecke committed
183

Torsten Ensslin's avatar
Torsten Ensslin committed
184 185 186 187
This is the interface that all objects derived from :class:`Operator` must implement.
In addition, :class:`Operator` objects can be added/subtracted, multiplied, chained
(via the :class:`__call__` method) and support pointwise application of functions like
:class:`exp()`, :class:`log()`, :class:`sqrt()`, :class:`conjugate()` etc.
Martin Reinecke's avatar
Martin Reinecke committed
188

189 190 191 192

Linear Operators
================

Philipp Arras's avatar
Philipp Arras committed
193
A linear operator (represented by NIFTy5's abstract :class:`LinearOperator`
Martin Reinecke's avatar
Martin Reinecke committed
194 195
class) is derived from `Operator` and can be interpreted as an
(implicitly defined) matrix. Since its operation is linear, it can provide some
Torsten Ensslin's avatar
Torsten Ensslin committed
196
additional functionality which is not available for the more generic :class:`Operator`
Martin Reinecke's avatar
Martin Reinecke committed
197
class.
198

Martin Reinecke's avatar
Martin Reinecke committed
199 200 201 202

Operator basics
---------------

203 204
There are four basic ways of applying an operator :math:`A` to a field :math:`f`:

Martin Reinecke's avatar
Martin Reinecke committed
205 206 207 208
- direct application: :math:`A\cdot f`
- adjoint application: :math:`A^\dagger \cdot f`
- inverse application: :math:`A^{-1}\cdot f`
- adjoint inverse application: :math:`(A^\dagger)^{-1}\cdot f`
209

Martin Reinecke's avatar
Martin Reinecke committed
210 211
(Because of the linearity, inverse adjoint and adjoint inverse application
are equivalent.)
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

These different actions of an operator ``Op`` on a field ``f`` can be invoked
in various ways:

- direct multiplication: ``Op(f)`` or ``Op.times(f)`` or ``Op.apply(f, Op.TIMES)``
- adjoint multiplication: ``Op.adjoint_times(f)`` or ``Op.apply(f, Op.ADJOINT_TIMES)``
- inverse multiplication: ``Op.inverse_times(f)`` or ``Op.apply(f, Op.INVERSE_TIMES)``
- adjoint inverse multiplication: ``Op.adjoint_inverse_times(f)`` or ``Op.apply(f, Op.ADJOINT_INVERSE_TIMES)``

Operator classes defined in NIFTy may implement an arbitrary subset of these
four operations. This subset can be queried using the
:attr:`~LinearOperator.capability` property.

If needed, the set of supported operations can be enhanced by iterative
inversion methods;
for example, an operator defining direct and adjoint multiplication could be
Martin Reinecke's avatar
Martin Reinecke committed
228
enhanced by this approach to support the complete set. This functionality is
229 230 231 232 233 234 235 236 237 238 239 240 241 242
provided by NIFTy's :class:`InversionEnabler` class, which is itself a linear
operator.

Direct multiplication and adjoint inverse multiplication transform a field
living on the operator's :attr:`~LinearOperator.domain` to one living on the operator's :attr:`~LinearOperator.target`, whereas adjoint multiplication
and inverse multiplication transform from :attr:`~LinearOperator.target` to :attr:`~LinearOperator.domain`.

Operators with identical domain and target can be derived from
:class:`EndomorphicOperator`; typical examples for this category are the :class:`ScalingOperator`, which simply multiplies its input by a scalar
value, and :class:`DiagonalOperator`, which multiplies every value of its input
field with potentially different values.

Further operator classes provided by NIFTy are

Martin Reinecke's avatar
Martin Reinecke committed
243 244
- :class:`HarmonicTransformOperator` for transforms from a harmonic domain to
  its counterpart in position space, and their adjoint
245
- :class:`PowerDistributor` for transforms from a :class:`PowerSpace` to
Martin Reinecke's avatar
Martin Reinecke committed
246
  an associated harmonic domain, and their adjoint
247 248 249 250
- :class:`GeometryRemover`, which transforms from structured domains to
  unstructured ones. This is typically needed when building instrument response
  operators.

Martin Reinecke's avatar
Martin Reinecke committed
251

Martin Reinecke's avatar
Martin Reinecke committed
252 253
Syntactic sugar
---------------
Martin Reinecke's avatar
Martin Reinecke committed
254

Martin Reinecke's avatar
Martin Reinecke committed
255
Nifty5 allows simple and intuitive construction of altered and combined
256 257
operators.
As an example, if ``A``, ``B`` and ``C`` are of type :class:`LinearOperator`
Martin Reinecke's avatar
Martin Reinecke committed
258
and ``f1`` and ``f2`` are of type :class:`Field`, writing::
259

Martin Reinecke's avatar
Martin Reinecke committed
260
    X = A(B.inverse(A.adjoint)) + C
261 262 263 264 265 266 267 268 269 270 271
    f2 = X(f1)

will perform the operation suggested intuitively by the notation, checking
domain compatibility while building the composed operator.
The combined operator infers its domain and target from its constituents,
as well as the set of operations it can support.
The properties :attr:`~LinearOperator.adjoint` and
:attr:`~LinearOperator.inverse` return a new operator which behaves as if it
were the original operator's adjoint or inverse, respectively.


Philipp Arras's avatar
Philipp Arras committed
272 273
Operators
=========
274

Philipp Arras's avatar
Philipp Arras committed
275
Operator classes (represented by NIFTy5's abstract :class:`Operator` class) are used to construct
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
276
the equations of a specific inference problem.
Philipp Arras's avatar
Philipp Arras committed
277
Most operators are defined via a position, which is a :class:`MultiField` object,
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
278
their value at this position, which is again a :class:`MultiField` object and a Jacobian derivative,
279
which is a :class:`LinearOperator` and is needed for the minimization procedure.
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
280

Philipp Arras's avatar
Philipp Arras committed
281
Using the existing basic operator classes one can construct more complicated operators, as
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
282
NIFTy allows for easy and self-consinstent combination via point-wise multiplication,
Philipp Arras's avatar
Philipp Arras committed
283
addition and subtraction. The operator resulting from these operations then automatically
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
284 285 286 287
contains the correct Jacobians, positions and values.
Notably, :class:`Constant` and :class:`Variable` allow for an easy way to turn
inference of specific quantities on and off.

Philipp Arras's avatar
Philipp Arras committed
288
The basic operator classes also allow for more complex operations on operators such as
289
the application of :class:`LinearOperators` or local non-linearities.
Philipp Arras's avatar
Philipp Arras committed
290 291
As an example one may consider the following combination of ``x``, which is an operator of type
:class:`Variable` and ``y``, which is an operator of type :class:`Constant`::
292

Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
293
	z = x*x + y
294

Philipp Arras's avatar
Philipp Arras committed
295
``z`` will then be an operator with the following properties::
296 297

	z.value = x.value*x.value + y.value
Martin Reinecke's avatar
Martin Reinecke committed
298
	z.position = Union(x.position, y.position)
299 300 301
	z.jacobian = 2*makeOp(x.value)


Philipp Arras's avatar
Philipp Arras committed
302
Basic operators
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
303
------------
Philipp Arras's avatar
Philipp Arras committed
304
# FIXME All this is outdated!
305

Philipp Arras's avatar
Philipp Arras committed
306
Basic operator classes provided by NIFTy are
307

Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
308
- :class:`Constant` contains a constant value and has a zero valued Jacobian.
Philipp Arras's avatar
Philipp Arras committed
309
  Like other operators, it has a position, but its value does not depend on it.
310 311 312
- :class:`Variable` returns the position as its value, its derivative is one.
- :class:`LinearModel` applies a :class:`LinearOperator` on the model.
- :class:`LocalModel` applies a non-linearity locally on the model.
Martin Reinecke's avatar
Martin Reinecke committed
313
	value and Jacobian are combined into corresponding :class:`MultiFields` and operators.
Martin Reinecke's avatar
tweaks  
Martin Reinecke committed
314

315

Philipp Arras's avatar
Philipp Arras committed
316 317
Advanced operators
------------------
318

Philipp Arras's avatar
Philipp Arras committed
319
NIFTy also provides a library of more sophisticated operators which are used for more
320 321
specific inference problems. Currently these are:

Philipp Arras's avatar
Philipp Arras committed
322 323 324
- :class:`AmplitudeOperator`, which returns a smooth power spectrum.
- :class:`InverseGammaOperator`, which models point sources which follow a inverse gamma distribution.
- :class:`CorrelatedField`, which models a diffuse log-normal field. It takes an amplitude operator
325 326 327
	to specify the correlation structure of the field.


328 329
.. _minimization:

Martin Reinecke's avatar
Martin Reinecke committed
330

331 332 333
Minimization
============

Martin Reinecke's avatar
Martin Reinecke committed
334 335 336 337 338 339
Most problems in IFT are solved by (possibly nested) minimizations of
high-dimensional functions, which are often nonlinear.


Energy functionals
------------------
340

Philipp Arras's avatar
Philipp Arras committed
341
In NIFTy5 such functions are represented by objects of type :class:`Energy`.
Martin Reinecke's avatar
Martin Reinecke committed
342 343
These hold the prescription how to calculate the function's
:attr:`~Energy.value`, :attr:`~Energy.gradient` and
Martin Reinecke's avatar
Martin Reinecke committed
344
(optionally) :attr:`~Energy.metric` at any given :attr:`~Energy.position`
Martin Reinecke's avatar
Martin Reinecke committed
345
in parameter space.
Martin Reinecke's avatar
Martin Reinecke committed
346
Function values are floating-point scalars, gradients have the form of fields
Martin Reinecke's avatar
Martin Reinecke committed
347
living on the energy's position domain, and metrics are represented by
Martin Reinecke's avatar
Martin Reinecke committed
348
linear operator objects.
349

Martin Reinecke's avatar
Martin Reinecke committed
350 351
Energies are classes that typically have to be provided by the user when
tackling new IFT problems.
Philipp Arras's avatar
Philipp Arras committed
352
Some examples of concrete energy classes delivered with NIFTy5 are
Martin Reinecke's avatar
Martin Reinecke committed
353
:class:`QuadraticEnergy` (with position-independent metric, mainly used with
Philipp Arras's avatar
Philipp Arras committed
354
conjugate gradient minimization) and :class:`~nifty5.library.WienerFilterEnergy`.
355

Martin Reinecke's avatar
Martin Reinecke committed
356 357 358

Iteration control
-----------------
Martin Reinecke's avatar
Martin Reinecke committed
359 360

Iterative minimization of an energy reqires some means of
Martin Reinecke's avatar
Martin Reinecke committed
361
checking the quality of the current solution estimate and stopping once
Martin Reinecke's avatar
Martin Reinecke committed
362 363 364
it is sufficiently accurate. In case of numerical problems, the iteration needs
to be terminated as well, returning a suitable error description.

Philipp Arras's avatar
Philipp Arras committed
365
In NIFTy5, this functionality is encapsulated in the abstract
Martin Reinecke's avatar
Martin Reinecke committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
:class:`IterationController` class, which is provided with the initial energy
object before starting the minimization, and is updated with the improved
energy after every iteration. Based on this information, it can either continue
the minimization or return the current estimate indicating convergence or
failure.

Sensible stopping criteria can vary significantly with the problem being
solved; NIFTy provides one concrete sub-class of :class:`IterationController`
called :class:`GradientNormController`, which should be appropriate in many
circumstances, but users have complete freedom to implement custom sub-classes
for their specific applications.


Minimization algorithms
-----------------------

Martin Reinecke's avatar
Martin Reinecke committed
382 383 384 385 386 387 388 389 390 391 392 393 394
All minimization algorithms in NIFTy inherit from the abstract
:class:`Minimizer` class, which presents a minimalistic interface consisting
only of a :meth:`~Minimizer.__call__` method taking an :class:`Energy` object
and optionally a preconditioning operator, and returning the energy at the
discovered minimum and a status code.

For energies with a quadratic form (i.e. which
can be expressed by means of a :class:`QuadraticEnergy` object), an obvious
choice of algorithm is the :class:`ConjugateGradient` minimizer.

A similar algorithm suited for nonlinear problems is provided by
:class:`NonlinearCG`.

Martin Reinecke's avatar
Martin Reinecke committed
395
Many minimizers for nonlinear problems can be characterized as
Martin Reinecke's avatar
Martin Reinecke committed
396 397 398 399 400 401 402 403 404

- first deciding on a direction for the next step
- then finding a suitable step length along this direction, resulting in the
  next energy estimate.

This family of algorithms is encapsulated in NIFTy's :class:`DescentMinimizer`
class, which currently has three concrete implementations:
:class:`SteepestDescent`, :class:`VL_BFGS`, and :class:`RelaxedNewton`.
Of these algorithms, only :class:`RelaxedNewton` requires the energy object to
Martin Reinecke's avatar
Martin Reinecke committed
405
provide a :attr:`~Energy.metric` property, the others only need energy
Martin Reinecke's avatar
Martin Reinecke committed
406 407
values and gradients.

Martin Reinecke's avatar
Martin Reinecke committed
408 409 410 411 412
The flexibility of NIFTy's design allows using externally provided
minimizers. With only small effort, adapters for two SciPy minimizers were
written; they are available under the names :class:`NewtonCG` and
:class:`L_BFGS_B`.

Martin Reinecke's avatar
Martin Reinecke committed
413 414 415 416

Application to operator inversion
---------------------------------

Martin Reinecke's avatar
Martin Reinecke committed
417 418 419 420 421 422 423 424 425 426
It is important to realize that the machinery presented here cannot only be
used for minimizing IFT Hamiltonians, but also for the numerical inversion of
linear operators, if the desired application mode is not directly available.
A classical example is the information propagator

:math:`D = \left(R^\dagger N^{-1} R + S^{-1}\right)^{-1}`,

which must be applied when calculating a Wiener filter. Only its inverse
application is straightforward; to use it in forward direction, we make use
of NIFTy's :class:`InversionEnabler` class, which internally performs a
Martin Reinecke's avatar
Martin Reinecke committed
427
minimization of a :class:`QuadraticEnergy` by means of the
Martin Reinecke's avatar
Martin Reinecke committed
428
:class:`ConjugateGradient` algorithm.