grale.plotutil
This module defines various plotting utilities, as well as classes to help you make animations.
Defaults
- grale.plotutil.setDefaultAngularUnit(x)
In various plot functions you can specify which angularUnit should be used when visualizing the results. If it is set to
"default"
, then the value set by this function will be used.
- grale.plotutil.getDefaultAngularUnit()
In various plot functions you can specify which angularUnit should be used when visualizing the results. If it is set to
"default"
, then the value returned by this function will be used. It can be set withsetDefaultAngularUnit()
.
DensInfo and LensInfo
- exception grale.plotutil.LensInfoException
An exception that’s raised in case of an error with a LensInfo object
- class grale.plotutil.DensInfo(densitypointsOrPixels, bottomleft, topright, isPixels=False)
In case you’d like to use the
plotDensity
functions to create a plot based on a 2D NumPy array, you can pass an instance of this class to the plot function. This can come in handy when creating the difference, average or standard deviation of several mass maps fromLensInfo
objects.- __init__(densitypointsOrPixels, bottomleft, topright, isPixels=False)
Initialize the object so that the 2D NumPy array densitypointsOrPixels describes an area from bottomleft to topright. The isPixels flag informs the constructor if the specified data contains values at regularly spaced points or values inside pixels. As the pixels can be calculated from the points, but not the other way around, use points if you have the option.
- getArea()
Returns a dictionary with
topright
andbottomleft
entries as specified in the constructor. Can come in handy when passing these arguments to another constructor to describe the same area.
- getBottomLeft()
Returns the bottomleft argument that was passed in the constructor, as a NumPy array.
- getDensityPixels(renderer='default', feedbackObject='default')
Returns the density pixels, based on the densitypoints from the constructor. The densitypoints describe the values at specific points laid out on a grid; the pixels convert these values so that each entry becomes the integrated value over a pixel.
In an instance of the
DensInfo
type, the renderer and feedbackObject arguments are not used; in an instance of the derived classLensInfo
, they can be used to specify the renderer to use to speed up the calculation, and with feedbackObject you can specify a particular feedback mechanism.
- getDensityPoints(renderer='default', feedbackObject='default')
Returns the densitypoints NumPy array that was set in the constructor.
- getNumXPixels()
Returns the number of pixels in the X direction
- getNumXPoints()
Returns the number of points in the X direction
- getNumYPixels()
Returns the number of pixels in the Y direction
- getNumYPoints()
Returns the number of points in the Y direction
- getTopRight()
Returns the topright argument that was passed in the constructor, as a NumPy array.
- getXPointCoordinates(repeat=True)
Returns the X coordinates for the densitypoints grid, based on the bottomleft and topright values from the constructor.
- getYPointCoordinates(repeat=True)
Returns the Y coordinates for the densitypoints grid, based on the bottomleft and topright values from the constructor.
- class grale.plotutil.LensInfo(lens=None, bottomleft=None, topright=None, center=[0, 0], size=None, numx=None, numy=None, numxy=511, Ds=None, Dds=None, zd=None, zs=None, cosmology='default')
This type of object can be used in the
plotImagePlane
andplotDensity
functions, and is based on a single or multi lensplane scenario.- __init__(lens=None, bottomleft=None, topright=None, center=[0, 0], size=None, numx=None, numy=None, numxy=511, Ds=None, Dds=None, zd=None, zs=None, cosmology='default')
Constructs an object of this type.
- Arguments:
lens: for a single lens plane setting, this should be an instance of a
GravitationalLens
derived class. In case a multi-lensplane scenario is to be used, this should be an array of(lens, redshift)
tuples or a MultiPlaneContainer lens (which holds the same information).bottomleft and topright, or size and center: using these arguments you can describe the area for which plot information should be calculated.
numx and numy, or numxy: the number of columns and rows (or both) of the grid for which properties (deflection angles, densities, …) should be calculated.
Ds and Dds, or zs (and possibly zd): these are relevant for image plane calculations, for which the position of the source needs to be known. For a single lens plane setting, you can either set both Ds and Dds, or both zs and zd. In case a multi lens plane setting is used, you only need to specify zs. Note that when using the redshift values, a cosmological model must be known as well.
cosmology: the cosmological model to be used. This is necessary when redshifts are to be used.
- static fromLensPlane(lensPlane)
Creates a LensInfo instance based on a previously created
LensInfo <grale.images.LensInfo>]
instance.
- getDensityPoints(renderer='default', feedbackObject='default')
Returns the densities on a 2D NumPy grid that corresponds to the area in the constructor, calculations if needed. With the renderer argument, you can specify a specific renderer to speed up the calculation, and with feedbackObject you can specify a particular feedback mechanism.
- getImagePlane(renderer='default', feedbackObject='default')
Returns the
ImagePlane
orMultiImagePlane
instance that corresponds to the settings from the constructor, performing the necessary calculations if needed. With the renderer argument, you can specify a specific renderer to speed up the calculation, and with feedbackObject you can specify a particular feedback mechanism.
- getIntegratedMass(renderer='default', feedbackObject='default')
Based on the grid as set in the constructor, this returns the total estimated mass in the area, performing the necessary calculations if needed. With the renderer argument, you can specify a specific renderer to speed up the calculation, and with feedbackObject you can specify a particular feedback mechanism.
- getLens()
Returns the lens (or multiple lenses) that was set at construction time.
- getLensPlane(renderer='default', feedbackObject='default')
Returns the
LensPlane
orMultiLensPlane
instance that corresponds to the settings from the constructor, performing the necessary calculations if needed. With the renderer argument, you can specify a specific renderer to speed up the calculation, and with feedbackObject you can specify a particular feedback mechanism.
- setSourceDistances(Ds, Dds)
Sets the source distances to Ds and Dds.
- setSourceRedshift(zs)
Sets source redshift to zs.
PlotException
- exception grale.plotutil.PlotException
An exception that will be thrown in case something goes wrong when plotting
Functions to create matplotlib plots
- grale.plotutil.plotDensity(lensOrLensInfo, renderer='default', feedbackObject='default', angularUnit='default', densityUnit=1.0, axes=None, axImgCallback=None, **kwargs)
Creates a 2D plot of the situation specified in lensOrLensInfo.
In case you just want the calculations to be performed (for example because you need the calculated density pixels) but you don’t want an actual plot, you can set the axes parameter to False.
- Arguments:
lensOrLensInfo: this can either be a
GravitationalLens
instance or an instance ofLensInfo
or evenDensInfo
. In case it’s only a gravitational lens, an estimate of the relevant area will be used.renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
densityUnit: by default, the density will be in kg/m^2, but another unit can be specified here.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
axImgCallback: if specified, this callback function will be called with the object returned by
imshow
as argument.kwargs: these parameters will be passed on to the imshow function in matplotlib.
- grale.plotutil.plotDensityContours(lensOrLensInfo, renderer='default', feedbackObject='default', angularUnit='default', densityUnit=1.0, axes=None, axImgCallback=None, levels=None, **kwargs)
Creates a contour plot of the mass density specified in lensOrLensInfo.
In case you just want the calculations to be performed (for example because you need the calculated density pixels) but you don’t want an actual plot, you can set the axes parameter to False.
- Arguments:
lensOrLensInfo: this can either be a
GravitationalLens
instance or an instance ofLensInfo
or evenDensInfo
. In case it’s only a gravitational lens, an estimate of the relevant area will be used.renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
densityUnit: by default, the density will be in kg/m^2, but another unit can be specified here.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
axImgCallback: if specified, this callback function will be called with the object returned by
contour
as argument.kwargs: these parameters will be passed on to the contour function in matplotlib.
- grale.plotutil.plotDensityMixed3D2D(lensOrLensInfo, colMapSurface='viridis', colMapContour='gray_r', colMapThickContour='gray_r', labelSize=9, azimuth_angle=-75, elevation_angle=15, angularUnit='default', densityUnit=1.0, vmin=None, vmax=None, offset2D=-3, contourLevels=None, thickContourLevels=None, flipX=False, drawExtra2D=1, drawExtra3D=1, contourKw={'linestyles': 'dotted', 'linewidths': 0.25}, thickContourKw={'linestyles': '-', 'linewidths': 1}, xLabel=None, yLabel=None, zLabel=None, adjustProjectionCallback=None, contourfLevels=200, crStride=8, drawZeroSheet=True, zeroKw={'alpha': 0.5, 'edgecolor': None, 'facecolor': 'gray'}, axes=None)
TODO
- grale.plotutil.plotDensitiesAtImagePositions(lens, imgList, angularUnit='default', densityUnit=1.0, horCoordFunction=<function <lambda>>, axes=None, densFunction=None, reduceMethod=None, forceAverage=None, **kwargs)
Plots the densities at the image position for the specified lens.
The function returns what is used to create the plot, but _without_ rescaling by the angularUnit or densityUnit: coordinates of the images based on horCoordFunction, average and standard deviation based on densFunction, and the number of sub-lenses that were used in calculating average and stddev.
- Arguments:
lens: the gravitational lens to use, if this is an average of several sublenses, average densities and error bars will be shown.
imgList: list of images to use; if these are extended images, the average position of an image is used to evaluate the density at.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
densityUnit: by default, the density will be in kg/m^2, but another unit can be specified here.
horCoordFunction: the resulting plot will plot the densities on the vertical axis, and this function specifies how the 2D coordinates of the points should be converted to a single value on the horizontal axis. By default, just the X-coordinate of a point is used.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
densFunction: if not specific, a lens’s
getSurfaceMassDensity
will get used to obtain the density, but otherwise this function is called with a lens model, position and imgList entry as parameters. This can be (ab)used to create similar plots with different values, like the relative mass density or even magnification.reduceMethod: needed for extended images, must be one of
"avgpos"
,"merge"
or"none"
. For"avgpos"
, the average position of an image is calculated first, and at that position the densities are calculated. For"merge"
, the densities at all image points are calculated first, then merged for each extended image (mergeDensityMeasurementsAndAveragePositions()
is used for this). The position for an image is also taken to be the average of its points. When set to"none"
, all image points are treated individually.forceAverage: TODO
kwargs: these parameters will be passed on to the plot or errorbar functions in matplotlib.
- grale.plotutil.plotImagePlane(lensOrLensInfo, sources=[], renderer='default', feedbackObject='default', angularUnit='default', subSamples=9, sourceRgb=(0, 1, 0), imageRgb=(1, 1, 1), bgRgb=(0, 0, 0), caustColor='blue', caustKw={}, critColor='red', critKw={}, plotCaustics=True, plotCriticalLines=True, plotSources=True, plotImages=True, evenError=True, axes=None, axImgCallback=None, processRenderPixels=None, **kwargs)
Create a matplotlib-based plot of image plane and/or source plane for certain lens parameters in lensOrLensInfo. You can also use this function to create the necessary calculated mappings but not the plot, by setting axes to False. This can be useful to create a
LensPlane
andImagePlane
instance using a specific renderer to speed up the calculation.- Arguments:
lensOrLensInfo: this can either be a
GravitationalLens
instance or an instance ofLensInfo
. In case it’s only a gravitational lens, an estimate of the corners will be used, and both Ds and Dds will be set to 1.0 (only the value of Dds/Ds matters, and will be one in this case).sources: one or more sources for which the lens effect will be calculated. A source can either be a source shape, or a dictionary with the following entries:
shape
: the actual source shapez
, orDs
andDds
: redshift or angular diameter distances for this source.
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
subSamples: each pixel is sub-sampled sqrt(subSamples) times in x- and y- direction, to be able to roughly approximate the integration that’s needed over the surface area of a pixel. This parameter is passed to
ImagePlane.renderImages
andImagePlane.renderSources
.sourceRgb: the RGB color, or a list of RGB colors, (each component is a number between 0 and 1) that should be given to a pixel that lies within a source.
imageRgb: the RGB color, or a list of RGB colors, (each component is a number between 0 and 1) that should be given to a pixel that lies within an image.
caustColor: color, or list of colors, for the caustics.
caustKw: dictionary describing keyword arguments for the matplotlib’s
plot
function for drawing the caustics.critColor: color, or list of colors, for the critical lines.
critKw: dictionary describing keyword arguments for the matplotlib’s
plot
function for drawing the critical lines.bgRgb: the RGB color for the background.
plotCaustics: boolean value, or list of values, that indicates if the caustics for a source should be drawn on the plot.
plotCriticalLines: boolean value, or list of values, that indicates if the critical lines for a source should be drawn on the plot.
plotSources: boolean value (or list) that indicates if the sources should be drawn on the plot.
plotImages: boolean value (or list) that indicates if the images should be drawn on the plot.
evenError: by default, the function will raise an exception if the number of pixels in the x or y-direction is even, because for simple lenses odd pixel numbers work better. In case you don’t care for this, set the flag to False and this will stop the calculation.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
axImgCallback: if specified, this callback function will be called with the object returned by
imshow
as argument.processRenderPixels: a function that is called before the final
imshow
call; it is the array that’s returned by this function (if specified) that is plotted. This can be used to combine the images of several sources with a galaxy image for example.kwargs: these parameters will be passed on to the imshow function in matplotlib.
- grale.plotutil.plotAverageDensityProfile(lensOrLensInfo, thetaMax, center=[0.0, 0.0], thetaSteps=512, phiSteps=512, angularUnit='default', densityUnit=1.0, axes=None, renderer='default', feedbackObject='default', thetaMin=0.0, **kwargs)
Creates a plot of the circularly averaged density profile.
- Arguments:
lensOrLensInfo: information about the gravitational lens for which the plot should be made. To obtain the lens density values on a grid, for numerical integration, the
plotDensity()
function is called first (without actually plotting the results). There, you can find more information about this parameter.thetaMax: the angular radius up to which the plot should be made.
center: the center of the circular averaging.
thetaSteps: to do the calculations numerically the maximum radius thetaMax will be divided into this many parts.
phiSteps: to average the mass density at a specific radius, the circular region will be subdivided into this many parts.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
densityUnit: by default, the density will be in kg/m^2, but another unit can be specified here.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
thetaMin: TODO
- grale.plotutil.plotIntegratedMassProfile(lensOrLensInfo, thetaMax, center=[0.0, 0.0], thetaSteps=512, phiSteps=512, angularUnit='default', massUnit=1.0, axes=None, renderer='default', feedbackObject='default', **kwargs)
Creates a plot of the circularly integrated mass profile. The arguments are the same as for
plotAverageDensityProfile()
.
- grale.plotutil.plotSubdivisionGrid(cells, angularUnit='default', axes=None, squareScale=1.0, **kwargs)
Creates a plot of the specified subdivision grid, obtained by a function from the
grid
module for example.- Arguments:
cells: the grid cells.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
squareScale: TODO
kwargs: these parameters will be passed on to the imshow function in matplotlib.
- grale.plotutil.plotImagesData(imgDat, angularUnit='default', plotHull=False, skipTriangles=False, axes=None, fillTriangles=False, imagePlotOptionsFunction=None, shearLengthMultiplier=1, shearPlotOptionsFunction=None)
Creates a plot of either a single images data set, or a list of them. In the first case, each image will be drawn with a different color, in the second, each complete images data set (typically for a specific source) uses a different color.
- Arguments:
imgDat: either a list, typically to plot several sources at once, or a single entry. The entry itself can be an instance if
ImagesData
or can be a dictionary of which theimgdata
key contains such anImagesData
object.angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
plotHull: a flag indicating if the convex hull of the points for each image should be plotted as well. Can be useful for visualizing which points belong to the same image, in case no triangulation is stored in the
ImagesData
instance.skipTriangles: if this flag is set, triangles stored in the
ImagesData
instance will not be drawn.axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well.
fillTriangles: if set, the triangulation, if present, will be filled.
imagePlotOptionsFunction: TODO
shearLengthMultiplier: TODO
shearPlotOptionsFunction: TODO
- grale.plotutil.plotShearComponents(thetas, gamma1, gamma2, lengthMultiplier, angularUnit='default', axes=None, **kwargs)
TODO
Functions to create gnuplot plots
- grale.plotutil.plotDensityGnuplot(lensOrLensInfo, fileNameBase=None, numX=75, numY=75, renderer='default', feedbackObject='default', angularUnit='default', densityUnit=1.0, axes=None, color=True, xlabel='X', ylabel='Y', zlabel='Z', plot3D=True, rotationX=45, rotationZ=45, showAxes=True, flipX=False, gnuplotExe='gnuplot', convertExe='convert')
Creates a gnuplot-based plot of the mass density of the lens, either as a 3D surface plot or as a 2D plot. Various files with names starting with fileNameBase are generated. If you only want to generate these files, but not visualize them in a plot immediately, you can set axes to False.
- Arguments:
lensOrLensInfo: this can either be a
GravitationalLens
instance or an instance ofLensInfo
or evenDensInfo
. In case it’s only a gravitational lens, an estimate of the relevant area will be used.fileNameBase: the generated gnuplot file will have this name, ending with
.gnuplot
. Similarly, the generated eps file will start with this and end with.eps
. If set to None, no output files will be generated, but the result may still be shown.numX: the number of points in the x-direction used to create the surface or 2D plot.
numY: the number of points in the y-direction used to create the surface or 2D plot.
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
densityUnit: by default, the density will be in kg/m^2, but another unit can be specified here.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
color: a boolean that indicates if the plot should use colors or grayscale only.
xlabel: the label for the x-axis.
ylabel: the label for the y-axis.
zlabel: the label for the z-axis.
plot3D: flag indicating if a 3D surface plot should be generated, or a 2D plot.
rotationX: if a 3D surface plot is created, this specifies the number of degrees the plot is rotated around the x-axis before showing.
rotationZ: if a 3D surface plot is created, this specifies the number of degrees the plot is rotated around the z-axis before showing.
showAxes: flag that indicates if the axes should be shown on the plot.
flipX: a boolean that indicates if the x-axis should go from right to left.
gnuplotExe: the
gnuplot
command.convertExe: the
convert
command. This program is used to show the generated plot using matplotlib: the eps generated by gnuplot is converted to a PNG file which is then shown using matplotlib.
- grale.plotutil.plotImagePlaneGnuplot(lensOrLensInfo, fileNameBase=None, sources=[], plotCaustics=True, plotCriticalLines=True, plotSources=True, plotImages=True, renderer='default', feedbackObject='default', angularUnit='default', subSamples=9, evenError=True, axes=None, color=True, xlabel='X', ylabel='Y', grid=False, flipX=False, gnuplotExe='gnuplot', convertExe='convert')
Creates a gnuplot-based plot of the image plane/source plane that corresponds to the situation specified in lensOrLensInfo, saving various files with names starting with fileNameBase. If you only want to generate these files, but not visualize them in a plot immediately, you can set axes to False.
- Arguments:
lensOrLensInfo: this can either be a
GravitationalLens
instance or an instance ofLensInfo
. In case it’s only a gravitational lens, an estimate of the corners will be used, and both Ds and Dds will be set to 1.0 (only the value of Dds/Ds matters, and will be one in this case).fileNameBase: the generated gnuplot file will have this name, ending with
.gnuplot
. Similarly, the generated eps file will start with this and end with.eps
. If set to None, no output files will be generated, but the result may still be shown.sources: a list of source shapes that should be used to calculate the images from.
plotCaustics: boolean value that indicates if the caustics should be drawn on the plot.
plotCriticalLines: boolean value that indicates if the critical lines should be drawn on the plot.
plotSources: boolean value that indicates if the sources should be drawn on the plot.
plotImages: boolean value that indicates if the images should be drawn on the plot.
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
subSamples: each pixel is sub-sampled sqrt(subSamples) times in x- and y- direction, to be able to roughly approximate the integration that’s needed over the surface area of a pixel. This parameter is passed to
ImagePlane.renderImages
andImagePlane.renderSources
.evenError: by default, the function will raise an exception if the number of pixels in the x or y-direction is even, because for simple lenses odd pixel numbers work better. In case you don’t care for this, set the flag to False and this will stop the calculation.
axes: the default will cause a new plot to be created, but you can specify an existing matplotlib axes object as well. The value False has a special meaning: in that case, the calculations will be performed as usual, but an actual plot will not be created.
color: a boolean that indicates if the plot should use colors or grayscale only.
xlabel: the label for the x-axis.
ylabel: the label for the y-axis.
grid: a boolean that indicates if a grid should be shown as well.
flipX: a boolean that indicates if the x-axis should go from right to left.
gnuplotExe: the
gnuplot
command.convertExe: the
convert
command. This program is used to show the generated plot using matplotlib: the eps generated by gnuplot is converted to a PNG file which is then shown using matplotlib.
Functions to create FITS files
- grale.plotutil.createEmptyFITS(xPix, yPix, angularWidthDeg, angularHeightDeg, raCenterDeg, decCenterDeg, xpCenter, ypCenter)
Helper function to create an empty FITS file.
Arguments:
xPix: number of pixels in the FITS file in the X-direction
yPix: number of pixels in the FITS file in the Y-direction
angularWidthDeg: the angular width of the file, in degrees
angularHeightDeg: the angular height of the file, in degrees
raCenterDeg: the right ascension of the xpCenter pixel, in degrees
decCenterDeg: the declination of the center ypCenter pixel, in degrees
xpCenter: the pixel position that corresponds to raCenterDeg
ypCenter: the pixel position that corresponds to decCenterDeg
- grale.plotutil.plotDensityFITS(lensInfo, raCenterDeg, decCenterDeg, renderer='default', feedbackObject='default')
Creates a FITS image (actually a HDUList that can then be saved) for the mass density in lensInfo.
- Arguments:
raCenterDeg: the right ascension of the center of the rendered image plane, in degrees.
decCenterDeg: the declination of the center of the rendered image plane, in degrees
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
- grale.plotutil.plotImagePlaneFITS(lensInfo, sources, raCenterDeg, decCenterDeg, renderer='default', feedbackObject='default', plotSources=False)
Creates a FITS image (actually a HDUList that can then be saved) for a lensing situation.
- Arguments:
lensInfo: an instance of
LensInfo
sources: a list of source shapes that should be used to calculate the images from.
raCenterDeg: the right ascension of the center of the rendered image plane, in degrees.
decCenterDeg: the declination of the center of the rendered image plane, in degrees
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
plotSources: if True, the sources themselves will be plotted instead of the images.
- grale.plotutil.calculateDeflectionAndDerivativesForFITS(lens, numXY, angularSize, lensCenterRARec, renderer='default', feedbackObject='default')
This function calculates a
lens plane
for a specified gravitational lens, and does this in such a way that the results (deflection angles and their derivatives) can be stored in a FITS file.- Arguments:
lens: the gravitational lens for which the properties should be calculated.
numXY: an array of length two containing the number of pixels in X and Y dimentsions for the resulting FITS file and grids.
angularSize: an array of length two containing the angular size in X and Y directions respectively.
lensCenterRARec: for the World Coordinate System in the FITS file, the lens center is assumed to be located at these coordinates. This is an array of length two, of which the first entry is the right ascension and the second is the declination.
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
When successful, the function returns a dictionary containing the following entries:
emptyfits
: an empty fits file, in which one of the calculated properties could be stored.alpha_x
: a grid containing the x-component of the deflection angle at the corresponding location.alpha_xy
: a grid containing the y-component of the deflection angle at the corresponding location.alpha_xx
: a grid containing the x-derivative of the x-component of the deflection angle.alpha_yy
: a grid containing the y-derivative of the y-component of the deflection angle.alpha_xy
: a grid containing the y-derivative of the x-component of the deflection angle.lensplane
: the lens plane that was calculated. Note that if similar grids would be obtained from this lens plane instance directly, they would not be the same! Due to the fact that the right ascension axis goes from right to left, the values would be mirrored in this direction.
Example:
import grale.lenses as lenses import grale.plotutil as plotutil import grale.cosmology as cosmology from grale.constants import * cosm = cosmology.Cosmology(0.7, 0.3, 0, 0.7) # Calculate angular diameter distances for redshift zd, zs = 0.5, 1.0 Dd = cosm.getAngularDiameterDistance(zd) Ds = cosm.getAngularDiameterDistance(zs) Dds = cosm.getAngularDiameterDistance(zd, zs) # Create a lens lens = lenses.PlummerLens(Dd, { "width": 2*ANGLE_ARCSEC, "mass": 1e13*MASS_SUN }) # Create the properties as well as an empty FITS file in which they can be stored w = 20*ANGLE_ARCSEC ra = 6.6485541367*ANGLE_DEGREE dec = 17.1619006374*ANGLE_DEGREE r = plotutil.calculateDeflectionAndDerivativesForFITS(lens, [1024, 1024], [ w, w], [ ra, dec], renderer = "openmp") # Calculate the convergence (kappa), and write it to a FITS file fitsFile = r["emptyfits"] axx, ayy = r["alpha_xx"], r["alpha_yy"] fitsFile[0].data = 0.5*(Dds/Ds)*(axx+ayy) fitsFile.writeto(open("plummer_dens.fits", "wb"))
Interactive plotting
- grale.plotutil.plot3DInteractive(X, Y, Z, height=600, xlabel='X', ylabel='Y', zlabel='Z', flipX=False, initialCamera=None, visJSoptions=None, maxPoints=128, visJS='https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js', visCSS='https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css', canvas2svgJS='https://cdn.rawgit.com/gliffy/canvas2svg/master/canvas2svg.js', fileSaverJS='https://cdn.rawgit.com/eligrey/FileSaver.js/b4a918669accb81f184c610d741a4a8e1306aa27/FileSaver.js')
Helper function to creates an interative plot in a jupyter notebook, using vis.js.
- Arguments:
X: a NY x NX numpy array containing the X coordinates of the plot region.
Y: similar X, but with Y coordinates of the plot region.
Z: also a NY x NX array, containing the Z-values of the surface to be plotted.
height: the height of the plot area.
xlabel: the label for the x-axis.
ylabel: the label for the y-axis.
zlabel: the label for the z-axis.
flipX: a boolean that indicates if the x-axis should go from right to left.
initialCamera: when manipulating the view, you’ll see information about ‘horizontal’, ‘vertical’ and ‘distance’ information change. To make the initial view correspond to a particular setting, put these values in a dictionary with these keys.
visJSoptions: this is for advanced use only, you can pass extra options to a vis.Graph3d instance this way.
maxPoints: an exception will be raised if the array dimensions exceed this value, this is to prevent accidentally plotting something with very high detail, which would become very slow.
visJS: URL to the vis.js JavaScript library.
visCSS: URL to the vis.js CSS file.
canvas2svgJS: URL to the canvas2svg.js file.
fileSaverJS: URL to FileSaver.js file
- grale.plotutil.plotDensityInteractive(lensOrLensInfo, numX=75, numY=75, height=600, xlabel='X', ylabel='Y', zlabel='Z', angularUnit='default', densityUnit=1.0, renderer='default', feedbackObject='default', flipX=False, initialCamera=None, visJSoptions=None, maxPoints=128, visJS='https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js', visCSS='https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css', canvas2svgJS='https://cdn.rawgit.com/gliffy/canvas2svg/master/canvas2svg.js', fileSaverJS='https://cdn.rawgit.com/eligrey/FileSaver.js/b4a918669accb81f184c610d741a4a8e1306aa27/FileSaver.js')
Creates an interactive 3D plot of the mass density specified in lensOrLensInfo.
- Arguments:
lensOrLensInfo: this can either be a
GravitationalLens
instance or an instance ofLensInfo
or evenDensInfo
. In case it’s only a gravitational lens, an estimate of the relevant area will be used.numX: the number of points in the x-direction used to create the surface or 2D plot.
numY: the number of points in the y-direction used to create the surface or 2D plot.
height: the height of the plot area.
xlabel: the label for the x-axis.
ylabel: the label for the y-axis.
zlabel: the label for the z-axis.
angularUnit: the angular unit that should be used in the plot. The pre-defined constants can be useful here.
densityUnit: by default, the density will be in kg/m^2, but another unit can be specified here.
renderer: this parameter can be used to specify a specific renderer to speed up the calculation.
feedbackObject: can be used to specify a particular feedback mechanism.
flipX: a boolean that indicates if the x-axis should go from right to left.
initialCamera: when manipulating the view, you’ll see information about ‘horizontal’, ‘vertical’ and ‘distance’ information change. To make the initial view correspond to a particular setting, put these values in a dictionary with these keys.
visJSoptions: this is for advanced use only, you can pass extra options to a vis.Graph3d instance this way.
maxPoints: an exception will be raised if the array dimensions exceed this value, this is to prevent accidentally plotting something with very high detail, which would become very slow.
visJS: URL to the vis.js JavaScript library.
visCSS: URL to the vis.js CSS file.
canvas2svgJS: URL to the canvas2svg.js file.
fileSaverJS: URL to FileSaver.js file
Helper functions
- grale.plotutil.estimatePlotScale(lens, DdsOverDs=1.0, center=[0, 0])
This is a function to estimate the scale that needs to be used when plotting the image plane of a gravitational lens. If you’re creating a simulated lens for example, you may not yet know on what scale it should be plotted to show something useful. This function tries to return a relevant scale that can be used when specifying the lower-left and upper-right corners for a plot.
- Arguments:
lens: the
gravitational lens
that you’re interested in.DdsOverDs: the fraction Dds/Ds that’s relevant for the scenario.
center: in case the lens is significantly off-center, specifying an estimate of the center can help in determining a relevant scale.
- grale.plotutil.quickLensInfo(lens)
For the specified lens, this creates a lensInfo dictionary that can be used on several plotting functions. The corners of the region are estimated using
estimatePlotScale()
, and Ds and Dds entries are set to 1.0.
- grale.plotutil.getDensitiesAtImagePositions(lens, imgList, reducePositionFirst, densFunction=None, forceAverage=None)
- Gets the densities at the image position for the specified lens,
mainly intended for use with a lens that’s an average of several lenses.
- Arguments:
lens: the gravitational lens to use
imgList: list of images to use
densFunction: if not specific, a lens’s
getSurfaceMassDensity
will get used to obtain the density, but otherwise this function is called with a lens model, position and imgList entry as parameters. This can be (ab)used to create similar plots with different values, like the relative mass density or even magnification.reducePositionFirst: if
True
, an extended image will first be reduced to a single point (the average position of the points in the image), and at this position the densities will be evaluated.forceAverage: TODO
- grale.plotutil.mergeDensityMeasurementsAndAveragePositions(l)
For density measurements returned by
getDensitiesAtImagePositions()
this function can be used to merge all measurements for each extended image, and use its average position as the point at which the densities are associated.
Classes to create animations
- class grale.plotutil.Animation(fileName, startPos, endPos, steps, fps)
A helper class to create an animation. This class generates an mp4 or webm file as soon as an instance is created. To visualize the result immediately in an notebook, you can use the
NotebookAnimation
class.To generate a useful plot, you’ll need to override at least the onDraw member function. Additional initialization can be done in the onInit member function.
While the class can be used to generated animations that involve gravitational lensing, this is certainly not required. Example:
import grale.plotutil as plotutil import numpy as np class MyAnim(grale.plotutil.Animation): def __init__(self): super(MyAnim, self).__init__("test.mp4", [0], [10], 100, 25) def onInit(self, axes): pass def onDraw(self, pos, axes): x = np.linspace(0, 6, 100) y = np.cos(x+pos) axes.clear() axes.plot(x, y) # Constructing an instance of this class will immediately start rendering the frames. anim = MyAnim()
- __init__(fileName, startPos, endPos, steps, fps)
Initializes the object and immediately starts rendering the frames into a movie.
- Arguments:
fileName: the name of the file that will contain the animation. By default an mp4 movie will be created, but if the filename ends with
.webm
, a webm format will be used instead.startPos, endpos and steps: for each frame, a position that goes from startpos to endpos in the number of iterations specified by steps, will be passed to the onDraw member function. Both startpos and endpos should be arrays, tuples or vectors, with the same dimension.
fps: the frames generated by the animation (will be steps frames) will be played back at this number of frames per second.
- onDraw(pos, axes)
For each frame, a position between startPos and endPos (from the constuctor) is determined and this value is passed as pos. You can then draw something on the axes object that corresponds to this position.
- onFrame(frameNum, totalFrames)
This method is called to provide you with feedback. By default it writes the progress to stdout; override to do something different.
- class grale.plotutil.NotebookAnimation(fileName, *args, **kwargs)
This is derived from the
Animation
class and not only creates the movie but also embeds it in a notebook for immediate visualization. The constructor takes the same arguments as the one fromAnimation
.Note that only a reference to the movie is embedded, so the movie will not be saved inside the notebook itself.
- onFrame(frameNum, totalFrames)
This method is called to provide you with feedback. By default it writes the progress to stdout; override to do something different.