Convolvables

Prysm features a rich implemention of Linear Shift Invariant (LSI) system theory. Under this mathematical ideal, the transfer function is the product of the Fourier transform of a cascade of components, and the spatial distribution of intensity is the convolution of a cascade of components. These features are usually used to blur objects or images with Point Spread Functions (PSFs), or model the transfer function of an opto-electronic system. Within prysm there is a class Convolvable which objects and PSFs inherit from. You should rarely need to use the base class, except when subclassing it with your own models or objects or loading a source image.

The built-in convolvable objects are Slits, Pinholes, Tilted Squares, and Siemens Stars. There are also two components, PixelAperture and OLPF, used for system modeling.

[1]:
from prysm import Convolvable, Slit, Pinhole, TiltedSquare, SiemensStar, PixelAperture, OLPF
[2]:
s = Slit(width=1, orientation='crossed')  # diameter, um
p = Pinhole(width=1)
t = TiltedSquare(angle=8, background='white', sample_spacing=0.05, samples=256)  # degrees
star = SiemensStar(spokes=32, sinusoidal=False, background='white', sample_spacing=0.05, samples=256)
pa = PixelAperture(width_x=5)  # diameter, um
ol = OLPF(width_x=5*0.66)

Objects that take a background parameter will be black-on-white for background=white, or white-on-black for background=black. Two objects are convolved via the conv method, which returns self on a new Convolvable instance and is chainable,

[3]:
# monstrosity = s.conv(p).conv(t).conv(star).conv(pa).conv(ol)

Some models require sample spacing and samples parameters while others do not. This is because prysm has many methods of executing an FFT-based Fourier domain convolution under the hood. If an object has a known analytical Fourier transform, the class has an analytic_ft method which has abscissa units of reciprocal microns. If the analytic FT is present, it is used in lieu of numerical data. Models that have analytical Fourier transforms also accept sample_spacing and samples parameters, which are used to define a grid in the spatial domain. If two objects with analytical Fourier transforms are convolved, the output grid will have the finer sample spacing of the two inputs, and the larger span or window width of the two inputs.

The Convolvable constructor takes only four parameters,

[4]:
import numpy as np
x = y = np.linspace(-20,20,256)
z = np.random.uniform(size=256**2).reshape(256,256)
c = Convolvable(data=z, unit_x=x, unit_y=y, has_analytic_ft=False)

has_analytic_ft has a default value of False.

Minimal labor is required to subclass Convolvable. For example, the Pinhole implemention is simply:

[5]:
# need from prysm import mathops as m if you want to actually use this

class Pinhole(Convolvable):
    def __init__(self, width, sample_spacing=0.025, samples=0):
        self.width = width

        # produce coordinate arrays
        if samples > 0:
            ext = samples / 2 * sample_spacing
            x, y = m.linspace(-ext, ext, samples), m.linspace(-ext, ext, samples)
            xv, yv = m.meshgrid(x, y)
            w = width / 2
            # paint a circle on a black background
            arr = m.zeros((samples, samples))
            arr[m.sqrt(xv**2 + yv**2) < w] = 1
        else:
            arr, x, y = None, m.zeros(2), m.zeros(2)

        super().__init__(data=arr, unit_x=x, unit_y=y, has_analytic_ft=True)

    def analytic_ft(self, unit_x, unit_y):
        xq, yq = m.meshgrid(unit_x, unit_y)
        # factor of pi corrects for jinc being modulo pi
        # factor of 2 converts radius to diameter
        rho = m.sqrt(xq**2 + yq**2) * self.width * 2 * m.pi
        return m.jinc(rho).astype(config.precision)

which is less than 20 lines long.

Convolvable objects have a few convenience properties and methods. slice_x and its y variant exist and behave the same as slices on subclasses of OpticalPhase such as Pupil and Interferogram. plot_slice_xy also works the same way. shape is a convenience wrapper for .data.shape, and support_x, support_y, and support mimic the equivalent diameter properties on OpticalPhase.

show and show_fourier behave the same way as plot2d methods found throughout prysm, except there are xlim and ylim parameters, which may be either single values, taken to be symmetric axis limits, or length-2 iterables of lower and upper limits.

Finally, Convolvable objects may be initialized from images,

[6]:
from prysm import sample_files
c = Convolvable.from_file(sample_files('boat.png'), scale=5)  # plate scale in um -- 5microns/pixel
c.data /= 255  # when initializing from files, normalization is left to the user
c.show()
[6]:
(<Figure size 640x480 with 2 Axes>,
 <matplotlib.axes._subplots.AxesSubplot at 0x7f9e85c47550>)

and written out as 8 or 16-bit images,

[7]:
p = 'foo.png'  # or jpg, any format imageio can handle
c.save(p, nbits=16)

In practical use, one will generally only use the conv, from_file, and save methods with any degree of regularity. The complete API documentation is below. Attention should be paid to the docstring of conv, as it describes some of the details associated with convolutions in prysm, their accuracy, and when they are used.

[8]:
help(c.conv)
Help on method conv in module prysm.convolution:

conv(other) method of prysm.convolution.Convolvable instance
    Convolves this convolvable with another.

    Parameters
    ----------
    other : `Convolvable`
        A convolvable object

    Returns
    -------
    `Convolvable`
        a convolvable that lacks an analytical fourier transform

    Notes
    -----
    The algoithm works according to the following cases:
        1.  Both self and other have analytical fourier transforms:
            - The analytic forms will be used to compute the output directly.
            - The output sample spacing will be the finer of the two inputs.
            - The output window will cover the same extent as the "wider"
              input.  If this window is not an integer number of samples
              wide, it will be enlarged symmetrically such that it is.  This
              may mean the output array is not of the same size as either
              input.
            - An input which contains a sample at (0,0) may not produce an
              output with a sample at (0,0) if the input samplings are not
              favorable.  To ensure this does not happen confirm that the
              inputs are computed over identical grids containing 0 to
              begin with.
        2.  One of self and other have analytical fourier transforms:
            - The input which does NOT have an analytical fourier transform
              will define the output grid.
            - The available analytic FT will be used to do the convolution
              in Fourier space.
        3.  Neither input has an analytic fourier transform:
            3.1, the two convolvables have the same sample spacing to within
                 a numerical precision of 0.1 nm:
                - the fourier transform of both will be taken.  If one has
                  fewer samples, it will be upsampled in Fourier space
            3.2, the two convolvables have different sample spacing:
                - The fourier transform of both inputs will be taken.  It is
                  assumed that the more coarsely sampled signal is Nyquist
                  sampled or better, and thus acts as a low-pass filter; the
                  more finaly sampled input will be interpolated onto the
                  same grid as the more coarsely sampled input.  The higher
                  frequency energy would be eliminated by multiplication with
                  the Fourier spectrum of the more coarsely sampled input
                  anyway.

    The subroutines have the following properties with regard to accuracy:
        1.  Computes a perfect numerical representation of the continuous
            output, provided the output grid is capable of Nyquist sampling
            the result.
        2.  If the input that does not have an analytic FT is unaliased,
            computes a perfect numerical representation of the continuous
            output.  If it does not, the input aliasing limits the output.
        3.  Accuracy of computation is dependent on how much energy is
            present at nyquist in the worse-sampled input; if this input
            is worse than Nyquist sampled, then the result will not be
            correct.

[ ]: