I want to do a simulation on Fraunhofer diffraction and for that purpose I chose to use numpy and matplotlib. What I need to do, is to specify a 2D aperture function and for that I can create a meshgrid of x and y values and assign a function z(x,y), which in this case should be complex. All this does not sound too complicated, but here’s where I bump into a problem.
How do you define a rectangular, or a triangular piece inside a meshgrid, such that inside the geometric figure z=1 and outside z=0?
Minimal working example, where to begin:
#! /bin/usr/env python
# Import environment
import numpy as np
x_ = np.linspace(0,1,255)
y_ = np.linspace(0,1,255)
x,y = np.meshgrid(x_,y_)
what to do next?
I tried to solve the problem differently:
- draw a figure using matplotlib
- encode the values of z by using different colours
- save the figure as a png
- import the png as a numpy array and decode the colours.
However, this puts severe restrictions on the values taken by the function z, which is the main reason I am searching for a different approach.
Thanks very much for anybody who can help me.
The two easiest options are to either use
matplotlib.nxutils.points_inside_polyor to usemahotas.polygon.fill_polygon. The latter is a bit faster, but requires installingmahotas.As an example of the first option:
Which yields (a boolean numpy array):
On a side note,
nxutilsis going to be depreciated at some point in favor of some of the path methods. In the future, you’ll probably want to do something along the lines of:However, that’s only in the github head at the moment.