grale.inversion

This module contains functions for gravitational lens inversion. The most straightforward method is to use the class InversionWorkSpace, which keeps track of the settings and provides an easier interface to the other functions. For absolute control however, the individual functions can still be used.

Defaults

grale.inversion.getDefaultInverter()

Convenience function in this module, just calls grale.inverters.getDefaultInverter()

grale.inversion.setDefaultInverter(x)

Convenience function in this module, just calls grale.inverters.setDefaultInverter()

InversionWorkSpace

class grale.inversion.InversionWorkSpace(zLens, regionSize=None, regionCenter=None, multiRegionInfo=None, inverter='default', renderer='default', feedbackObject='default', cosmology='default')

This class tries to make it more straightforward to perform lens inversions by automatically keeping track of the inversion region, the input images and several other settings.

Typically, you’d perform the following steps:

  • create an instance of the class, specifying the redshift to the lens, the cosmological model and the region for the inversion.

  • add the images data sets to be used in the inversion using calls to addImageDataToList().

  • create a uniform grid for a first inversion with setUniformGrid() and run the inversion with a call to invert().

  • based on the returned lens model, create a grid with smaller cells in regions with more mass using setSubdivisionGrid(), and again run the inversion with a call to invert().

  • repeat as needed/desired.

To get more control over the basis functions of which the weights will be optimized, you can also set basis functions directly (see e.g. addBasisFunctions()) and optimize their weights using invertBasisFunctions().

__init__(zLens, regionSize=None, regionCenter=None, multiRegionInfo=None, inverter='default', renderer='default', feedbackObject='default', cosmology='default')

Constructor for this class.

Arguments:
  • zLens: the redshift to the gravitational lens for a single lens plane inversion, or a list of redshifts for an (experimental) multi lens plane inversion.

  • regionSize and regionCenter: the width and height of the region in which the inversion should take plane, as well as its center. This will be used to base the grid dimensions on, but by default some randomness will be added (see e.g. setUniformGrid()). For a more complex setup, where multiple such regions (in the same lens plane) are needed, these can be set to None, and the multiRegionInfo parameter below can be used. While region information is not needed when invertBasisFunctions() or invertParametric() are used, at least one region needs to be defined, even if it is just a ‘dummy’ value.

    These are the default values in setUniformGrid() and setSubdivisionGrid() but can still be overridden there.

    In case of a multi-plane inversion, you can specify different sizes for each plane if desired, otherwise the same settings will be used for all planes.

  • multiRegionInfo: for a more complex lens, where several strong lensing regions are present, you may want to use several regions than can be subdivided as the inversion progresses. For a single lens plane, you can specify a Regions object, a dictionary with "regionSize" and "regionCenter" keys, or a list of these. For a multi-plane scenario, a list of Regions objects is needed, one for each lens plane.

  • inverter: specifies the inverter to be used. See the inverters

  • renderer: this parameter can be used to specify a specific renderer to speed up the calculation of the mass densities (used for the procedure with the subdivision grid)

  • feedbackObject: can be used to specify a particular feedback mechanism.

  • cosmology: an instance of Cosmology, describing the cosmological model that should be used throughout these inversions.

addBasisFunctions(basisFunctions, lpIdx=None)

Add basis functions that will be used in invertBasisFunctions(). Each entry in this list should be a dictionary with at least entries lens and center containing the lens model and position at which it should be placed. A mass parameter may be present as well, describing the relevant lensing mass of this basis function. If no such mass is specified, it will be estimated numerically as the mass inside (roughly) the image region.

In the final call to the invert function, the complete list is then passed as the gridInfoOrBasisFunctions argument. You may look there for some additional information.

In a multi-plane setting, lpIdx needs to be used to select a particular lens plane.

addBasisFunctionsBasedOnCurrentGrid(lensModelFunction=<function defaultLensModelFunction>, initialParameters=None, lpIdx=None)

The goal of this function is to add basis functions based on the grid that’s currently stored. The conversion of grid cells to basis functions is done using the function specified in lensModelFunction. The default for this argument is defaultLensModelFunction.

In general, this function takes three arguments:

  • operation: the name of the operation

  • operationInfo: information about the operation

  • parameters: additional parameters

First lensModelFunction is called with operation set to "start", operationInfo set to a dictionary with entries workspace (this workspace) and grid (the current grid), and parameters set to initialParameters. The return value of the function, let’s call this lensModelFunctionParameters, will be used as the parameters for subsequent calls to lensModelFunction

Then, for each grid cell in the current grid, lensModelFunction is called with operation set to "add", operationInfo a dictionary with keys size and center containing the length of a cell square side and (x,y) coordinates of the cell center respectively. The previously returned lensModelFunctionParameters is passed as the parameters argument.

In this second phase, the lensModelFunction should return a tuple of two things: the lens model for that grid cell, and (optionally) the relevant lensing mass for this basis function. The lens model, the center and optionally this mass is then added to a list, which is eventually processed by the addBasisFunctions() procedure.

In a multi-plane setting, lpIdx needs to be used to select a particular lens plane.

addImageDataToList(imgDat, zs, imgType, otherParameters={})

Adds the ImagesData instance in imgDat to the list of inputs. The corresponding redshift is zs, and imgType describes the type of input, e.g. "extendedimages". The otherParameters dictionary provides additional settings for this input set. See the usage documentation for other types and parameters.

For data with type "bayesellipticities", for the Bayesian weak lensing fitness measure, it is necessary to set zs to None. That data itself contains for each individual galaxy the redshift and measured ellipticities, so no global redshift is allowed to be set.

backProject(lens, typeFilter=['pointimages', 'extendedimages', 'pointgroupimages'])

Takes the information of the images that were added using addImageDataToList(), and projects the points back onto the respective source planes using the lens model lens. Note that only the basic, single core procedure is used to back-project the images.

The typeFilter can be used to prevent that e.g. the null space grid is back-projected as well. If set to None, then all added ImagesData entries will be used. If it is a list of strings, then an entry will only be considered if the the type that was specified is present in this list. The typeFilter can also be a function that’s used to filter the added entries: return True to include an entry, or False to ignore it. The function will receive two parameters: an index into the list of ImagesData instances, and a dictionary that contains the ImagesData object as well as distances and parameters.

calculateFitness(lensOrBackProjectedImages)

For the current grid, the current images data sets, calculate the fitness values for the specified parameter, which can be either a lens, or the already backprojected input images.

When you’ve received the final result after an inversion, calling this function with that lens as its argument should yield the same fitness values to a good approximation. Some differences may exist though, as different code is used in the genetic algorithm.

calculateParametricFitness(lensOrParameters, parametricLensDescription=None, returnLens=False, forceScales=None)

TODO

clearBasisFunctions(lpIdx='all')

Clears the list of basis functions that will be used in invertBasisFunctions(). In a multi-plane setting lpIdx can be used to only clear the basis funtion for a specific lens plane.

clearImageDataList()

Clears the list of images data information.

estimateStrongLensingMass(skipParamCheck=False)

Calls estimateStrongLensingMass with the images and lens distance that have been set for this inversion work space.

getBasisFunctions(lpIdx=None)

Returns the basis functions that have currently been stored, and of which the weights will be optimized when invertBasisFunctions() is called. In a multi-plane setting, lpIdx can be used to obtain the basis functions for a particular lens plane.

getCosmology()

Returns the cosmological model that was specified during initialization.

getGrid(lpIdx=None)

Retrieves the currently set grid, e.g. for plotting using plotSubdivisionGrid.

In a multi-plane setting, lpIdx specifies a particular lens plane.

getImageDataList()

Returns the list that contains the images data sets, and which is built up by successive calls to addImageDataToList().

getLensDistance(lpIdx=None)

Returns the angular diameter distance to the lens. In case a multi-plane setting is used, lpIdx needs to specify a particular lens plane.

invert(populationSize, **kwargs)

For the current grid, the current images data sets, run the genetic algorithm for the inversion. This calls the invert function in this module, which you can consult for other arguments that you can specify using keywords. In addition to the keyword arguments specified there, you can also specify gridSizeFactor, rescaleBasisFunctions and basisFunctionType which will be used to set the sizefactor, rescale and basistype parameters in the initialParameters of the addBasisFunctionsBasedOnCurrentGrid call that’s used internally. Note that in this function call the lensModelFunction argument is set to defaultLensModelFunction.

If the same arguments need to be set for each call of this method, you can use setDefaultInversionArguments() to set them. Note that the options passed in kwargs will override the settings stored by that function.

This function is now a convenience function, it first calls clearBasisFunctions, then addBasisFunctionsBasedOnCurrentGrid, and finally invertBasisFunctions.

invertBasisFunctions(populationSize, **kwargs)

For the lensing scenario specified in this InversionWorkSpace instance, this method calls the invert function, but instead of using a grid, a list of basis functions (arbitrary basic lens models) is used of which the weights need to be optimized by the genetic algorithm. function.

invertParametric(parametricLensDescription, populationSize, **kwargs)

This function uses the images that were added to the workspace to perform a parametric inversion using the invertParametric() function. A lens description and population size must be passed, other options to that function can be specified as keyword arguments.

setBasisFunctions(basisFunctions, lpIdx=None)

Convenience method, just calls clearBasisFunctions() followed by addBasisFunctions(). In a multi-plane setting, lpIdx needs to be used to select a particular lens plane.

setDefaultInversionArguments(**kwargs)

In case you want to pass the same keyword arguments to the invert function multiple times, you can specify them using this function and omit them in the invert call. The different keyword arguments you can pass are the ones from the core invert function.

setGrid(grid, lpIdx=None)

Usually, the functions setUniformGrid() and setSubdivisionGrid() will be used to control the grid (which in turn controls the layout of the basis functions). If this doesn’t suffice, you can provide a specific grid obtained by one of the functions in grid yourself using this function.

In a multi-plane setting, lpIdx specifies the lens plane for which this grid is relevant.

setRegionSize(regionSize=None, regionCenter=None, multiRegionInfo=None, lpIdx='all')

Set the inversion region, same as in the constructor: regionSize and regionCenter are the width, height and center of the region in which the inversion should take plane. This will be used to base the grid dimensions on, but by default some randomness will be added (see e.g. setUniformGrid()).

For a more complex setup, where multiple such regions (in the same lens plane) are needed, these can be set to None, and the multiRegionInfo parameter can be used. In this case, multiRegionInfo should be a Regions object, a dictionary with "regionSize" and "regionCenter" keys, or a list of these.

In a multi-plane scenario, lpIdx can be used to specify a particular lens plane for which the region should be set, otherwise the same region settings are used for each lens plane.

setStrongAndWeakBasisFunctions(strongSubDivInfo, weakSubDiv=None, weakRegionSize=None, weakRegionCenter=None, weakMultiRegionInfo=None, weakRandomFraction='onesquare', weakMassScale=None, ignoreWLMassInMassScaleSearch=False, strongExcludeFunction=None, strongCheckSubDivFunction=None, weakExcludeFunction=None, strongLensModelFunction=<function defaultLensModelFunction>, strongLensModelInitialParams={}, weakLensModelFunction=<function defaultLensModelFunction>, weakLensModelInitialParams={})

This is a convenience function for strong&weak inversions. It sets basis functions based on a strong lensing grid (uniform or subdivision grid) as well as a uniform grid for the weak lensing region. It returns a tuple containing the created grids for strong and weak lensing regions respectively. Use invertBasisFunctions() to start the inversion.

Arguments:
  • strongSubDivInfo: this can either be a number, causing a uniform subdivision grid to be created for the strong lensing region (see setUniformGrid()). Alternatively, it can be a tuple (lens, minSubDiv, maxSubDiv) which will be used to create a subdivision grid through a call to setSubdivisionGrid(), or more explicitly a dictionary containing keys "lens", "mindiv", "maxdiv" and optionally "startsubdiv".

  • weakSubDiv: this should be a number that specifies the uniform subdivision parameter for the setUniformGrid() call for the weak lensing region. If this is set to zero or None, the function will only create the strong lensing part.

  • weakRegionSize and weakRegionCenter: these specify the dimensions of the grid for the weak lensing area. The strong lensing size is by default the one that was specified in the constructor. If the weak lensing part should consist of different regions, the following weakMultiRegionInfo parameter can be used.

  • weakMultiRegionInfo: similar to multiRegionInfo from the constructor, but for the weak lensing grid. This allows more complex regions to be specified.

  • weakRandomFraction: the default will add a random offset to the weak lensing grid that’s based on the grid cell size. A different value will be passed directly to the setUniformGrid() function.

  • weakMassScale: while the strong lensing mass scale can be estimated from the observed multiple image sytems, a mass scale needs to be specified for the weak lensing area. The basis functions that are created for the uniform weak lensing grid, will have a total mass that’s equal to this value.

  • ignoreWLMassInMassScaleSearch: internally, the genetic algorithm will rescale the mass distribution, in some range around the estimated strong lensing mass. When weak lensing mass is included, this search should either be expanded (set massScaleSearchType to wide instead of regular), or the masses of the basis functions in the weak lensing area should not be counted in this search.

  • strongExcludeFunction and strongCheckSubDivFunction: for the strong lensing part, these are passed as excludeFunction and checkSubDivFunction arguments of setUniformGrid() and setSubdivisionGrid().

  • weakExcludeFunction: for the weak lensing part, this is passed as the excludeFunction argument of setUniformGrid().

  • strongLensModelFunction and strongLensModelInitialParams: based on the strong lensing grid that’s built, addBasisFunctionsBasedOnCurrentGrid() will be called to actually add basis functions. These parameters are passed as lensModelFunction and lensModelFunctionParameters of that function respectively.

  • weakLensModelFunction and weakLensModelInitialParams: same, but for the weak lensing grid.

setSubdivisionGrid(lensOrLensInfo, minSquares, maxSquares, startSubDiv=1, randomFraction=0.05, regionSize=None, regionCenter=None, multiRegionInfo=None, lensFilter=None, lensInfoFilter=None, lpIdx=None, excludeFunction=None, checkSubDivFunction=None)

Based on the lens that’s provided as input, create a subdivision grid where regions with more mass are subdivided further, such that the number of resulting grid cells lies between minSquares and maxSquares. By default, the procedure starts from a single large grid cell, but by setting startSubDiv to some other value N, you can start from a uniform NxN grid instead. For more information about the procedure, see MultiGridCreator.getSubdivisionGrid.

The usage of the randomFraction parameter is the same as in setUniformGrid(). If specified, regionSize, regionCenter or multiRegionInfo override the internally stored dimensions.

In a multi-plane setting, if lensOrLensInfo is a MultiPlaneContainer result returned from a previous invert call, the specified subdivision will be applied to each lens plane, using the corresponding inversion result for that lens plane. Alternatively, a single plane lens model or LensInfo instance can be used for a specific lens plane, but in that case lpIdx must be set to the correct lens plane index.

If specified, lensFilter can be used to apply some kind of filtering on the lens model, in case lensOrLensInfo refers to a gravitational lens instance. Similar filtering can be done for a LensInfo object by specifying the lensInfoFilter function. The first filter function needs to accept four parameters: the lens object, the bottom-left coordinate of a region, the top-right coordinate, and an lpIdx parameter for the lens plane under consideration. For the second filter function two parameters are passed, the LensInfo object and an lpIdx parameter. They should return a lens or LensInfo object respectively.

With excludeFunction you can determine if a grid cell should be excluded from the final grid, and with checkSubDivFunction you can specify if some grid cell may be subdivided further. Both parameters are passed on to MultiGridCreator.getSubdivisionGrid.

setUniformGrid(subDiv, randomFraction=0.05, regionSize=None, regionCenter=None, multiRegionInfo=None, lpIdx='all', excludeFunction=None)

Based on the size and center provided during initialization, create a uniform grid with subDiv subdivisions along each axis, resulting in subDiv`x`subDiv cells.

The randomFraction parameter controls some randomness in the grid positioning: if this is a number, then the center will be offset randomly in X and Y directions by a fraction of the grid size. You can also specify a function instead of a number. In that case, it will receive the region size and center as two arguments, and it should return a tuple containing the width and center of the actual grid to use. This gives you somewhat more freedom in adding randomness to the grid size and center.

If specified, regionSize, regionCenter or multiRegionInfo override the internally stored dimensions.

In a multi-plane scenario, lpIdx can be used to specify only one lens plane.

The excludeFunction parameter can be used to exclude certain regions from the generated grid, see MultiGridCreator.getUniformGrid for more information.

class grale.inversion.Regions(regionInfoList)

For free-form lens inversions, typically a grid based approach is used, where a square region is subdivided into smaller grid cells. A single lens plane can be covered by multiple such regions, in case the lens is relatively large and has distinct strong lensing parts. This class represents one or more of these regions, in a single lens plane. For a multi-plane scenario, multiple of these Regions objects could be used.

__init__(regionInfoList)

Construct an instance based on regionInfoList. In principle this should be a list of dictionaries with keys "size" and "center" (the latter is assumed to be (0, 0) if not present). It can also just be a single dictionary, as a shorthand for a list containing only this one entry.

getNumberOfRegions()

Returns the number of different regions that were specified in the constructor.

getRegions()

Returns the regions that were specified in the constructor.

Core functions

grale.inversion.estimateStrongLensingMass(Dd, images, skipParamCheck=False)

For a gravitational lens that’s located at angular diameter distance Dd, estimate the strong lensing mass based on the images data in images. Each entry in the images list should be a dictionary with at least these keys:

  • images: the ImagesData instance describing the images of a source

  • Ds and Dds: angular diameter distances to this source and from lens to source respectively.

Unless skipParamCheck is True, the dictionary should also have a params key, for futher parameters of this images data set. These params should also be a dictionary with at least a type field; the images data set is skipped unless this type field is either extendedimages, pointimages or pointgroupimages. This way, images data sets describing null space information for example, are skipped.

If there’s only one image, it will not be used in the mass estimate. Otherwise, the mass estimate for a single images data set will be estimated as the point mass that would be needed to create an Einstein ring with the same diameter as the images’ separaration. The final mass estimate is the average of these separate estimates.

grale.inversion.getDefaultModuleParameters(moduleName='general')

For the specified module name, query the default parameters.

grale.inversion.getDefaultConvergenceParameters(eaType)

Helper function to return the default convergence parameters for eaType

grale.inversion.getFullEASettings(eaType='GA', geneticAlgorithmParameters={}, convergenceParameters={})

This function is used to convert defaults for an evolutionary algorithm (EA) stage to full parameters. It is used by the invert() and invertMultiPlane() functions. The underlying code uses lists of different EA types, parameters for the algorithm, and parameters used to check for convergence. For convenience, certain predefined names can be expanded to such lists as well.

Arguments:

  • eaType: if this is a list, it should contain entries “GA”, “DE”, “JADE” or “RND”. It can also be a string, which in turn will be converted to such a list:

    • “GA” will be converted to [ “GA”, “GA” ], representing the two stage genetic algorithm approach, where the first one will typically use large mutations and the second one smaller ones.

    • “DE” is expanded to [ “DE” ], representing a classical diffential evolution optimization.

    • “JADE” is interpreted as [ “JADE” ], corresponding to the JADE algorithm, a self adapting differential evolution version.

    • “GA+JADE” is expanded to [ “GA”, “GA”, “JADE” ], the standard two-stage genetic algorithm followed by a JADE step to zoom in on the optimum more closely.

  • geneticAlgorithmParameters (should really be called just algorithmParameters): if this is a dictionary it will be replaced by a list containing as many copies of the dictionary as there are entries in the eaType list. Then, defaults for each EA are filled in, for settings that are not already present.

  • convergenceParameters: similar to the previous argument, if this is a dictionary it will first be copied a number of times. Then, defaults for the algorithm will be added.

grale.inversion.getInversionModuleUsage(moduleName='general')

Returns a usage description that’s provided by the specified genetic algorithm module. The usage information for the general module can be viewed here: usage

grale.inversion.calculateFitness(inputImages, zd, fitnessObjectParameters, lensOrBackProjectedImages, moduleName='general', cosmology=None)

You can pass several parameters in the same way as you would do for a lens inversion, but here you also specify the specific lens for which the relevant fitness measures should be calculated or the pre-calculated back-projected images.

Arguments:
  • inputImages: list of input images data instances that should be used in the inversion. See the invert() function for more information about the format.

  • zd: the redshift to the lens.

  • fitnessObjectParameters: parameters to be used when initializing the inversion module that’s specified

  • lensOrBackProjectedImages: either the gravitational lens model for which the fitness measures should be calculated, or a similar list as inputImages, for which the positions have already been mapped onto the source plane.

  • moduleName: name of the inversion module for the genetic algorithm.

  • cosmology: the cosmological model to use.

grale.inversion.invert(inputImages, basisFunctions, zd, Dd, popSize, moduleName='general', massScale='auto', allowNegativeValues=False, baseLens=None, sheetSearch='nosheet', fitnessObjectParameters=None, massScaleSearchType='regular', convergenceParameters={}, geneticAlgorithmParameters={}, returnNds=False, inverter='default', feedbackObject='default', cosmology=None, maximumGenerations=None, multiPopulationParameters=None, eaType='GA', useImagePositionRandomization=False)

Start the genetic algorithm to look for a gravitational lens model that’s compatible with the specified input images. This is a rather low-level function, it may be easier to use an instance of InversionWorkSpace instead. This function is for a single lens plane inversion, invertMultiPlane() is the multi-lens plane counterpart.

Arguments:
  • inputImages: a list of dictionaries with the following entries:

    • images: an ImagesData instance that describes the images of a source, the null space etc.

    • Ds and Dds: the angular diameter distances to this source.

    • params: not used for older inversion modules for the genetic algorithm, but for the general module, this should contain a dictionary with at least a type field, which can be e.g. pointimages or extendednullgrid (see the usage :ref:<usage-module-general> documentation). Other parameters may be set as well, e.g. you could set timedelay to False to ignore the time delay information in a particular images data instance.

  • basisFunctions: a list of entries containing basis function info. This parameter should be a list of dictionaries with the following entries:

    • lens: the lens model for this basis function.

    • center: the x,y position at which this lens model should be placed.

    • mass: the mass of this lens model, in the relevant area. Some models have a total mass parameter which would likely work fine, but not all models have this (e.g. a SIS lens or a mass sheet). You should then precalculate the mass in the strong lensing region (approximately) and store it in this entry. This is needed to the algorithm can estimate the total lensing mass of a certain combination of weighted basis functions.

  • zd: the redshift to the lens, used when calculating time delays (for other purposes the angular diameter distance will be used).

  • Dd: the angular diameter distance to the lens.

  • popSize: the size of the population in the genetic algorithm, e.g. 512.

  • moduleName: name of the inversion module for the genetic algorithm.

  • massScale: a rough estimate of the total mass of the gravitational lens. Set to "auto" or "auto_nocheck" to let the estimateStrongLensingMass() function provide this estimate automatically.

  • allowNegativeValues: by default, the weight of the basis functions are only allowed to be positive, to make certain that an overall positive mass density is obtained. In case corrections to a certain mass distribution are being sought, negative weights can be allowed by setting this parameter to False.

  • baseLens: in case an approximate solution is already known, it can be set as the lens to start from. In this scenario, the allowNegativeValues parameter is usually set to True. Note that when the base lens is specified, only the modifications to it are returned by the inversion routine, and if you want the full lens you need to combine this base lens and the modifications by using a CompositeLens instance.

  • sheetSearch: by default, only the basis functions for the grid cells are used. You can also allow a mass-sheet basis function, which may be useful as this kind of effect is difficult to model by a grid of basis functions. The traditional way to specify that a mass sheet basis function should be used is to set this to "genome". Alternatively you can specify a lens model to be used in a similar way, allowing you to e.g. use a mass disk. Of course, you can use any lens model here, it doesn’t need to be one resembling a mass sheet. The lens model is very roughly an upper limit in the sense that the search for this weight is initially between 0 and 1 (it is not included in the scaling loop used in the genetic algorithm).

  • fitnessObjectParameters: parameters for the lens inversion module for the generic algorithm. For the "general" module, more information can be found in the usage documentation.

  • massScaleSearchType: by default ("regular"), a relatively narrow mass range around the provided mass estimate will be explored. To make this search wider (which can be useful if you’re less certain of the total mass, e.g. when including weak lensing measurements over a larger area), you can set this parameter to "wide". It can also be set to "nosearch" to disable the mass scale search completely. Finally, mainly for testing purposes, it can also be set to a dictionary with the following entries:

    • startFactor

    • stopFactor

    • numIterations

    • firstIterationSteps

    • nextIterationSteps

  • convergenceParameters: see getFullEASettings().

  • geneticAlgorithmParameters: see getFullEASettings()

  • returnNds: by default, this function will return a single gravitational lens model. If there are several fitness measures however, the end result is actually a non-dominated set of models. The inversion module for the genetic algorithm has some default strategy for choosing one solution from this set. In case you’d like to get the complete non-dominated set instead, you can set this flag to True.

  • inverter: specifies the inverter to be used. See the inverters module for more information.

  • feedbackObject: can be used to specify a particular feedback mechanism.

  • cosmology: depending on the inversion algorithm, it may be necessary to specify a cosmological model.

  • maximumGenerations: if the genetic algorithm didn’t stop by itself after this many generations, stop it anyway. To test an inversion script completely, it can be useful to temporarily stop the genetic algorithm after only a small number of generations so that the code doesn’t take long to run (this is now actually merged into the convergenceParameters)

  • multiPopulationParameters: TODO: experimental multi-population feature

  • eaType: see getFullEASettings().

  • useImagePositionRandomization: if set to True, images that contain the "positionuncertainty" property will be randomized slightly according to this property’s value. This can be used to avoid overfitting.

grale.inversion.invertMultiPlane(inputImages, basisLensesAndRedshifts, popSize, moduleName='general', massScale='auto', allowNegativeValues=False, baseLenses=[], sheetSearch='nosheet', fitnessObjectParameters=None, massScaleSearchType='regular', convergenceParameters={}, geneticAlgorithmParameters={}, returnNds=False, deviceIndex='rotate', inverter='default', feedbackObject='default', maximumGenerations=None, cosmology=None, multiPopulationParameters=None, eaType='GA')

Perform a multi-plane lens inversion. This is a rather low-level function, it may be easier to use an instance of InversionWorkSpace instead.

Arguments:

  • inputImages: a list of dictionaries with the following entries:

    • images: an ImagesData instance that describes the images of a source, the null space etc.

    • z: the redshift of this source.

    • params: for the general_gpu module, this could contain a dictionary with at least a type field, which can be e.g. pointimages or extendednullgrid (see the usage documentation).

  • basisLensesAndRedshifts: A list representing the different lens planes. Each list entry is a dictionary with needs a key z to describe the plane’s redshift, and a key lenses that describes the basis functions in this lens plane. This lenses entry should be a list of dictionaries with the following entries:

    • lens: the lens model for this basis function.

    • center: the x,y position at which this lens model should be placed.

    • mass: the mass of this lens model, in the relevant area. Some models have a total mass parameter which would likely work fine, but not all models have this (e.g. a SIS lens or a mass sheet). You should then precalculate the mass in the strong lensing region (approximately) and store it in this entry. This is needed to the algorithm can estimate the total lensing mass of a certain combination of weighted basis functions.

  • popSize: the size of the population in the genetic algorithm, e.g. 512.

  • moduleName: name of the inversion module for the genetic algorithm.

  • massScale: a rough estimate of the total mass of the gravitational lens. Set to "auto" or "auto_nocheck" to let the estimateStrongLensingMass() function provide this estimate automatically.

  • allowNegativeValues: by default, the weight of the basis functions are only allowed to be positive, to make certain that an overall positive mass density is obtained. In case corrections to a certain mass distribution are being sought, negative weights can be allowed by setting this parameter to False.

  • baseLenses: for each lens plane, a base lens can be specified to which corrections can be applied.

  • sheetSearch: by default, only the basis functions for the grid cells are used. You can also allow a mass-sheet basis function, which may be useful as this kind of effect is difficult to model by a grid of basis functions. To do so, set this to "genome", in which a mass-sheet component will be added to each lens plane.

  • fitnessObjectParameters: parameters for the lens inversion module for the generic algorithm. For the "general" module, more information can be found in the usage documentation.

  • massScaleSearchType: by default ("regular"), a relatively narrow mass range around the provided mass estimate will be explored. To make this search wider (which can be useful if you’re less certain of the total mass, e.g. when including weak lensing measurements over a larger area), you can set this parameter to "wide". It can also be set to "nosearch" to disable the mass scale search completely. Finally, mainly for testing purposes, it can also be set to a dictionary with the following entries:

    • startFactor

    • stopFactor

    • numIterations

    • firstIterationSteps

    • nextIterationSteps

  • convergenceParameters: see getFullEASettings().

  • geneticAlgorithmParameters: see getFullEASettings().

  • returnNds: by default, this function will return a single gravitational lens model. If there are several fitness measures however, the end result is actually a non-dominated set of models. The inversion module for the genetic algorithm has some default strategy for choosing one solution from this set. In case you’d like to get the complete non-dominated set instead, you can set this flag to True.

  • deviceIndex: this multi-plane inversion uses a GPU to back-project the image data, and by setting a specific number, a specific device can be specified. To allow multiple GPUs to be used automatically, you can leave this to "rotate" and use an inverter with as many processes as you have GPUs.

  • inverter: specifies the inverter to be used. See the inverters module for more information.

  • feedbackObject: can be used to specify a particular feedback mechanism.

  • maximumGenerations: if the genetic algorithm didn’t stop by itself after this many generations, stop it anyway. To test an inversion script completely, it can be useful to temporarily stop the genetic algorithm after only a small number of generations so that the code doesn’t take long to run (this is now actually merged into the convergenceParameters)

  • cosmology: The cosmological model to use, to calculate the necessary angular diameter distances based on the specified redshifts.

  • multiPopulationParameters: TODO: experimental multi-population feature

  • eaType: see getFullEASettings().

grale.inversion.invertParametric(inputImages, parametricLensDescription, zd, Dd, popSize, moduleName='general', defaultInitialParameterFraction=0.1, clampToHardLimits=False, fitnessObjectParameters=None, convergenceParameters={}, geneticAlgorithmParameters={}, returnNds=False, inverter='default', feedbackObject='default', cosmology=None, maximumGenerations=None, eaType='JADE', deviceIndex='rotate', useImagePositionRandomization=False, allowUnusedPriors=False, numberOfRetraceSteps=5, retraceSourcePlaneThreshold='auto', allowEmptyInitialValueRange=False, forceScales=None, internalRecalcLens=None, internalCalcFitnessParams=None)

This is a low-level function, used by the similarly named function in InversionWorkSpace.

Arguments:
  • inputImages: describes the observed images and their properties, see invert() for a full description.

  • parametricLensDescription: a dictionary that describes the lens model and which parameters of the model can vary within which bounds. See the paramdesc module for more information.

  • zd: the redshift to the lens, used when calculating time delays (for other purposes the angular diameter distance will be used).

  • Dd: the angular diameter distance to the lens.

  • popSize: the size of the population in the genetic algorithm, e.g. 512.

  • moduleName: name of the inversion module for the evolutionary algorithm.

  • defaultInitialParameterFraction: this is passed onto the analyzeParametricLensDescription function.

  • clampToHardLimits: also passed to the same function.

  • fitnessObjectParameters: parameters for the lens inversion module for the evolutionary algorithm. For the "general" module, more information can be found in the usage documentation.

  • convergenceParameters: see getFullEASettings().

  • geneticAlgorithmParameters: see getFullEASettings()

  • returnNds: by default, this function will return a single gravitational lens model. If there are several fitness measures however, the end result is actually a non-dominated set of models. The inversion module for the genetic algorithm has some default strategy for choosing one solution from this set. In case you’d like to get the complete non-dominated set instead, you can set this flag to True.

  • inverter: specifies the inverter to be used. See the inverters module for more information.

  • feedbackObject: can be used to specify a particular feedback mechanism.

  • cosmology: depending on the inversion algorithm, it may be necessary to specify a cosmological model.

  • maximumGenerations: if the genetic algorithm didn’t stop by itself after this many generations, stop it anyway. To test an inversion script completely, it can be useful to temporarily stop the genetic algorithm after only a small number of generations so that the code doesn’t take long to run (this is now actually merged into the convergenceParameters)

  • eaType: see getFullEASettings().

  • deviceIndex: this parametric inversion uses a GPU to back-project the image data, and by setting a specific number, a specific device can be specified. To allow multiple GPUs to be used automatically, you can leave this to "rotate" and use an inverter with as many processes as you have GPUs.

  • useImagePositionRandomization: if set to True, images that contain the "positionuncertainty" property will be randomized slightly according to this property’s value. This can be used to avoid overfitting.

  • allowUnusedPriors: by default, if prior information is set on the parameters but the fitness measure cannot incorporate this, an error will be generated. To ignore this error, the flag can be set to True.

  • numberOfRetraceSteps: TODO, either a number or “disable”, for the bayesian strong lensing

  • retraceSourcePlaneThreshold: TODO, either “auto” or a number

  • allowEmptyInitialValueRange: TODO

  • forceScales: TODO

  • internalRecalcLens: For internal use

  • internalCalcFitnessParams: For internal use

grale.inversion.defaultLensModelFunction(operation, operationInfo, parameters)

This is the default lensModelFunction that’s used in InversionWorkSpace.addBasisFunctionsBasedOnCurrentGrid This default function will case the same behaviour as the classic grid based inversion procedure.

The initialParameters in that function call will be merged with a dictionary with the following entries:

  • basistype: defaults to plummer, but can also be square or gaussian

  • sizefactor: a specific value can be set here which converts the grid square size to a width of the basis function. The default value depends on the basis function type: 1.7 for plummer and 1.0 for the two others.

  • rescale (default is False): by default, the weight of a basis function is a measure of its total mass. This implies that smaller grid cells will correspond to larger densities, i.e. if you set all weights of the basis functions to the same value, the regions with smaller grid cells will have a considerably larger density. Since the usual approach will be to subdivide the regions that contain more mass into smaller grid cells, this does make sense and appears to produce very good results in most cases. To make this effect less pronounced, you can set this parameter to True, and the basis functions will be rescaled. The smaller grid cells will still have higher densities, but not as much as before (in case square basis functions were used, equal weights would generate equal densities irrespective of the grid size).

  • totalmass: the mass scale for the entire lensing region. In case it’s "auto", it will be estimated from the images stored in the InversionWorkSpace instance.

InversionException

exception grale.inversion.InversionException

An exception that’s generated if something goes wrong in a function provided by this module.