API Summary
Here we summarize the main objects within the pysersic framework and how they are most commonly used, along with summaries of their public methods and attributes.
For a more “step by step” guide to fitting a galaxy image, see the fititng tutorials.
Pysersic.priors
BasePrior(ABC)
The BasePrior object is responsible for the initial instantiation of any prior used by pysersic. Its main job is setting sky prior values. You should not have to interface directly with this class, unless you are trying to make your own Prior subclass.
Attribute Summary
sky_guess: central value of the sky pixel distributiosky_guess_err: estimate of the scatter aroundsky_guesssky_type: selected form of sky to fit.
Methods Summary
sample_sky_none(): method called when not sampling the sky (returns 0).sample_sky_flat(): method called when sampling a flat sky.sample_sky_tilted_plane()method called when sampling a tilted plane sky.
PySersicSourcePrior(BasePrior)
The PysersicSourcePrior inherits sky properties from the BasePrior and adds the relevant information needed to sample galaxy properties. This class is used directly when fitting a single galaxy in an image, and is wrapped by the class (below) which handles multi-source images.
Attribute Summary
profile_type: type of profile chosen to fit (e.g., “sersic”)
Method Summary
__repr__()The repr of this object prints out all of the parameters being fit and what their priors are.set_gaussian_prior(var_name,loc,scale): set a gaussian prior on one of the fit parameters, giving a loc and scale.set_uniform_prior(var-name, low, high): set a uniform prior on one of the fit parameters, giving a low and high value.set_truncated_gaussian_prior(var_name,loc,scale,low,high): set a truncated gaussian prior, giving the loc/scale of the gaussian and the low/high beyond which the distribution is truncatedset_custom_prior(var_name,prior_dist): Set a totally custom prior, giving anumpyro.dist.Distributionobject, and optionally aninfer.reparam.Reparamreparametrization as needed.check_vars(verbose=False): checks whether all variables for the profile type selected are set. Ifverbose=True, will print any missing variables and any extra variables. Will return true if all variables for the type are given with no extras.
PySersicMultiPrior(BasePrior)
The PySersicMultiPrior wraps the single prior object and sets up all the priors for multiple sources in one image.
Unlike for the single prior case, PySersicMultiPrior utilizes an input catalog to set the locations and priors for sources in the image. This catalog can be input in multiple formats so long as they are key-able, e.g., pandas.DataFrame, dict, or numpy.recordarray().
When you instantiate a PySersicMultiPrior object, provide the catalog, along with the sky type to fit, and a sky guess and sky guess error:
prior = PySersicMultiPrior(catalog,sky_type='flat',sky_guess=XXX,sky_guess_err=XXX)
The catalog has several required keys/columns:
x: pixel x position of sourcey: pixel y position of sourcer: estimate of effective radius in pixelsflux: estimate of the total source flux
Optionally, a column can be provided for theta:
theta:: position angle of source, in radians.
SourceProperties()
The SourceProperties class reads in an input image and derives properties relevant to the setting of prior parameters for fitting. When fitting a single source (and masking others), this class can be used to automatically set the priors before fitting. When fitting multiple sources in one image, a catalog is needed, but this class can still be used to generate estimates of the sky to feed into PySersicMultiPrior.
Setting up simply involves providing an image and/or mask:
sp = SourceProperties(image=image,mask=mask)
The class automatically measures the properties of the source in the image. You can visualize the measurements via the .visualize() method, which will show your image with a circle at the measured r-eff value, an x at the center position, and an arrow showing the measured theta. It won’t show the flux guess.
If the measurement (which uses astropy’s data_properties function) is off for some reason, you can set/overwrite any of the guesses via the methods (see below).
Attribute Summary
cat: theastropydata_propertiescatalog output, used to generate guesses.sky_guess: the measured sky value. By default, a ring of pixels at the edge of the image, median value.sky_guess_err: standard deviation of the ring of pixels around the image perimeter.flux_guess: estimate of the source flux usingsegment_fluxfrom theastropycatalog. If the flux guess is less than 0, it is set to 0.flux_guess_err: if flux estimate > 0, is by default2 * sqrt(flux_guess), if flux estimate is < 0, will be thesqrt(abs(flux guess)).r_eff_guess: estimate of r-effective, taken to be thekron radiusfrom theastropycatalog.r_eff_guess_err: taken to besqrt(r_eff_guess).theta_guess: estimate of position angle from catalog.position_guess: estimate of the x,y position of the source.
Method Summary
The main setters are used to set the value of the guesses needed to generate a prior. They are run (once) automatically, setting their relative attributes (above) based on image measurements. You can run them again if you have a better value than the defaults measured. Note that even if the guesses are somewhat off, the fit should still proceed normally.
set_sky_guess(sky_guess,sky_guess_err,n_pix_sample): set/overwrite/measure the sky,setting the relevant sky attributes. Running with guesses set toNone, it will measure the perimeter of the image, taking the median of the firstn_pix_samplerows and columns. It uses the masked image if a masked image was provided at instantiation.set_flux_guess(flux_guess,flux_guess_err): set/overwrite the flux and flux err guesses with a custom value.set_r_eff_guess(r_eff_guess,r_eff_guess_err): set/overwrite the measured guess/guess err for r-effective.set_theta_guess(theta_guess): set/overwrite the guess for theta.set_position_guess(position_guess): provide a tuple/list [x,y] of the position of the source.
The rest of the methods, beyond the parameter setters:
generate_prior(profile_type,sky_type): This takes all the properties that have been measured or set and returns thePySersicPriorobject instantiated using those values. Theprofile_typeis one ofsersic,doublesersic,pointsource,dev, orexp.visualize(figsize,cmap,scale): Allows one to quickly visualize the measured/set guesses over the data. All args are optional, but figsize, cmap, and an image scaling can be set.
Pysersic.rendering
BaseRenderer()
PixelRenderer(BaseRenderer)
FourierRenderer(BaseRenderer)
HybridRenderer(BaseRenderer)
Pysersic.pysersic
Once prior objects are made, the next main step is the fitting, which is handled in the pysersic.pysersic module.
BaseFitter(ABC)
The BaseFitter is the superclass of the more specific fitting methods (namely for fitting single vs multiple sources). You should not have to interact with this class directly unless you are building your own Fitters.
Attribute Summary
loss_func: the loss function being used.data: the data being fitrms: weight map (1/variance) corresponding to data; must be same shapepsf: map of the psf, pixelizedrenderer: type of renderer being used in the fitting.prior_dict: dictionary holding the prior info
After sampling, the following become available:
sampler: the sampler usedsampling_results:PySersicResultsobject containing the reuslts
Methods Summary
set_loss_func(): used to set the loss function (seeloss.py).set_prior(parameter,distribution): directly set the prior of a parameter using a numpyro distribution.sample(): sample; see api for all args. sets thesampling_resultsattribute.find_MAP(): use optimizer to find “best fit” model.estimate_posterior(): non-sampling methods of estimating posterior, uaing methodslaplace,svi-mvnorsvi-flow; see the paper for more details.
FitSingle(BaseFitter)
The FitSingle class is used for cases when fitting a single source in an image.
FitMulti(BaseFitter)
The FitMulti class is used to fit multiple sources in one image.
Pysersic.results
The Results class is responsible for holding the results of fitting/sampling, making it easy to visualize, extract, and otherwise do science with the fits.
PySersicResults()
The main class is the PySersicResults class, which knows about the data that was fit, the loss function and renderers used, and the actual outputs of the fits.
Attribute Summary
The following are mostly hyper-params or are just copied over from the fitter.
data: the datarms: the 1/variance mappsf: the pixelized psfmask: mask, if providedloss_func: loss function (callable) usedrenderer: renderer usedsvi_method_used: if svi was used to fit, which method was used
The actual results are stored in
idata: anarvizobject containing the fit results. All other things are mostly convenience terms derived from this.
Methods Summary
summary(): returnsaz.summary(self.idata); i.e., the summary data frame.corner(): wrapper aroundcorner.pyfor plotting a corner plot of the results. (returns the corner fig).retrieve_param_quantiles(quantiles,return_dataframe): returns a dict, or if specified, dataframe of the quantiles on each parameter. Quantiles are provided as a list-like, in decimal form (e.g., by default [0.16,0.5,0.84]).retrieve_med_std(): similar but for returning the median and std around the median for the properties.latex_table(): outputs a latex-friendly table for the fit (assuming a single fit). You can specify quantiles to use for the +/-.get_chains(): return the chains (wrapsax.extract()).compute_statistic(parameter,func): Compute an arbitrary statistic/computation on the chain for a given parameter.save_result(fname): Save the results to anasdffile. The input image/rms/mask/psf will be saved, as well as info on the loss func, renderer, and method used, along with the priors used, the best model, and the full posterior.
Other Reults Functions
Several other convenience functions are provided in the results module:
parse_multi_results(source_num): By default, the results object for a multi-source fit will have a lot of parameters, and will designate the different sources with_0,_1, etc., for each parameter. This function will parse that and return a results object for only one source at a time, as indicated by thesource_numinput. Using-1will reset to all sources.plot_image(): plots a summary image of the data (with mask if provided), weight map, and psf map side by side.plot_residual(): plots the data, the best fit model, and the residual between them side by side.