Index: trunk/doc/release.2015/ps1.analysis/analysis.tex
===================================================================
--- trunk/doc/release.2015/ps1.analysis/analysis.tex	(revision 40700)
+++ trunk/doc/release.2015/ps1.analysis/analysis.tex	(revision 40705)
@@ -417,10 +417,10 @@
 \end{itemize}
 
-\section{\nocode{psphot} Analysis Process}
+\section{Basic Analysis}
 
 \subsection{Overview}
 
-The \ippprog{psphot} analysis is divided into several major stages, as
-listed below.  
+The basic \ippprog{psphot} analysis is divided into several major
+stages, as listed below.
 
 \begin{enumerate}
@@ -441,7 +441,4 @@
   properties (aperture or PSF)
 
-\item {\bf Extended Source Analysis} Detailed measurements relevant to
-  galaxies and/or other extended (non-PSF) sources.
-
 \item {\bf Aperture corrections} Measure the curve-of-growth, spatial
   aperture variations, and background-error corrections.  
@@ -450,4 +447,12 @@
   difference image, variance image, etc, as selected.
 \end{enumerate}
+
+In addition to this basic sequence, additional analysis steps may be
+performed.  An ``extended source'' analysis mode is available to
+measure photometry and morphology of galaxies and other resolved
+sources.  Forced photometry may be performed for both point-like and
+extended sources.  A special mode is available for the photometry of
+sources detected in difference images.  These different modes are
+discussed in their own sections below.
 
 Table~\ref{tab:measurements} lists the types of
@@ -1938,5 +1943,222 @@
 \code{PM_SOURCE_MODE2_MATCHED} set.
 
-\subsection{Extended Source Analysis}
+\subsection{Aperture Correction and Total Aperture Fluxes}
+\label{sec:aperture.correction}
+
+A PSF model will always fail to describe the flux of the stellar
+sources at some level.  For high-precision photometry, we need to be
+able to correct for the difference between the PSF model fluxes and
+the total flux of the sources.  In the end, all astronomical
+photometry is in some sense a relative measurement between two images.
+Whether the goal is calibration of a science image taken at one
+location to a standard star image at another location, or the goal is
+simply the repetitive photometry of the same star at the same location
+in the image, it is always necessary to compare the photometry between
+two images.  If this measurement is to be consistent, then the
+measurement must represent the flux of the stars in the same way
+regardless of the conditions under which the images were taken, at
+least within some range of normal image conditions.  So, for example,
+two images with different image quality, or with different tracking
+and focus errors, will have different PSF models.  To the extent the
+PSF model is inaccurate, the measured flux of the same source in the
+two images will be different (even assuming all other atmospheric and
+instrumental effects have been corrected).  The amplitude of the error
+will by determined by how inconsistently the models represent the
+actual source flux.
+
+Aperture photometry attempts to avoid these problems, but introduces
+other difficulties.  In aperture photometry, if a large enough
+aperture is chosen, the amount of flux which is lost will be a small
+fraction of the total source flux.  Even more importantly, as the
+image conditions change, the amount lost will change by an even
+smaller fraction, at least for a large aperture.  This can be seen by
+the fact that the dominant variations in the image quality are in the
+focus, tracking and seeing.  All of these errors initially affect the
+cores of the stellar images, rather than the wide wings.  The wide
+wings are largely dominated by scattering in the optics and scattering
+in the atmosphere.  The amplitude and distribution of these two
+scattering functions do not change significantly or quickly for a
+single telescope and site.  Aperture photometry can then be used to
+correct the PSF photometry.
+
+The difficulty for aperture photometry is the need to make an accurate
+measurement of the local background for each source.  As the aperture
+grows, errors in the measurement of the sky flux start to become
+dominant.  If the aperture is too small, then variations in the image
+quality are dominant.  The brighter is the source, the smaller is the
+error introduced by the large size of the aperture.  However, the
+number of very bright stars is limited in any image, and of course the
+brighter stars are more likely to suffer from non-linearity or
+saturation.  
+
+\begin{figure*}[htbp]
+  \begin{center}
+ \includegraphics[width=\hsize,clip]{pics/{mag.resid.psf}.png}
+  \caption{\label{fig:mag.resid.psf} PSF Photometry demonstration.
+    The bottom panel shows the difference of the measured PSF
+    photometry for stars in the first image of the STS sequence
+    compared to the next 17 images, after correction for a relative
+    zero point.  Black dots are from stars for which both measurements
+    have {\tt PSF\_QF} $> 0.95$, while grey dots have lower {\tt
+      PSF\_QF} values.  The top three panels show histograms in three
+    instrumental magnitude ranges for the magnitude difference divided
+    by the reported measurement error: $N\sigma = (m_0 - m_1) /
+    \sqrt{\sigma_0^2 + \sigma_1^2}$.  The red curves are Gaussian fits
+    to these histograms, with the measured standard deviations in the
+    upper-right corners of the plots.  The instrumental magnitude
+    ranges are listed in the upper-left corners of the three plots and
+    the boundaries are marked as vertical red lines in the lower plot.
+  }
+  \end{center}
+\end{figure*}
+
+\begin{figure*}[htbp]
+  \begin{center}
+ \includegraphics[width=\hsize,clip]{pics/{mag.resid.aper}.png}
+  \caption{\label{fig:mag.resid.aper} Aperture Photometry
+    demonstration.  The plots show identical measurements to those in
+    Figure~\ref{fig:mag.resid.psf}, but for aperture photometry, as discussed in
+    Section~\ref{sec:aperture.correction}, rather than PSF photometry.}
+  \end{center}
+\end{figure*}
+
+In order to thread the needle between these effects, \ippprog{psphot}
+measures the aperture photometry on a modest-sized aperture, and then
+uses the PSF model to extrapolate to a large aperture.  When the PSF
+fluxes are calculated, the aperture flux for the modest-sized aperture
+is also determined.  The aperture is a circular aperture with radius
+set to a fixed multiple (\code{PSF_APERTURE_SCALE}) of $\sigma_w$, the
+width of the Gaussian window function determined based on the analysis
+of the second moments (see Section~\ref{sec:moments}).  For the PV3
+$3\pi$ analysis, the aperture window radius is $4.5 \times \sigma_w$,
+while the large reference aperture radius is set to 25 pixels
+(\code{PSF_REF_RADIUS} = 6\farcs4).  These corrected aperture
+magnitudes are saved in the output catalogs as \code{AP_MAG}, the
+uncorrected aperture magnitudes are saved as \code{AP_MAG_RAW}, and
+the radius used to measure the raw aperture flux is saved as
+\code{AP_MAG_RADIUS}.  The corresponding flux and the flux error are
+saved as \code{AP_FLUX} and \code{AP_FLUX_SIG}.
+
+With these aperture magnitudes in hand, it is now possible to make an
+average correction to the PSF magnitudes to bring the PSF and aperture
+magnitudes to the same system.  This correction is measured using the
+same stars from which the PSF model is measured, as long as the PSF
+magnitude error for the star is less than 0.03 mag.  The correction is
+calculated using the weighted average of the values $m_{\rm AP} -
+m_{\rm PSF}$.  Since the PSF may vary across the image, the correction
+is determined as a function of position in the image.  Like the PSF
+model, the 2D variations of the aperture correction may be modeled as
+a polynomial or via interpolation in a grid.  For the $3\pi$ PV3
+analysis, a grid with a maximum of $6\times 6$ samples per GPC1 chip
+image was used.  The reported PSF magnitudes for all objects have this
+aperture correction applied.
+
+% growth curve analysis in psphot:
+% in psphotChoosePSF : call psphotMakeGrowthCurve
+% in psphotMakeGrowthCurve : boolean GROWTH_FROM_SOURCES, use
+%% pmGrowthCurveGenerateFromSources or
+%% pmGrowthCurveGenerate (uses PSF model only)
+%% GROWTH_FROM_SOURCES is set to TRUE for default recipe
+
+%% ApTrend:
+%% in psphotApResid, called by psphotReadout near the end of the
+%% analysis
+%% ApTrend = f(x,y) for (apMag - psfMag) for psfMagErr <= 0.03
+%% apMag is growth curve corrected
+%% psfMag is raw
+
+%% raw psfMag and raw apMag are measured
+%% apMag = apMagRaw + growth curve correction (from apRadius to 25 pix
+%% = PSF_REF_RADIUS)
+%% psfMag = psfMagRaw + aperture trend (<ap - psf> + growth curve)
+
+% How important is this effect?  Consider a typical bright source with a
+% flux of (say) 40,000 counts in an image of background 1000 counts per
+% pixel, with FWHM of 4 pixels.  In principle, the flux of this source
+% should be measurable with an accuracy of roughly 0.57\%
+% ($\frac{\sqrt{40000 + 1000 \times 12}}{40000}$).  However, the
+% measurement of the sky is limited at some finite level by Poisson
+% statistics.  If we are required to use an aperture of (say) 25 pixels
+% in radius (eg, 5 arcseconds for an 0.2 arcsec / pixel detector), and
+% we have an annulus of twice this radius to measure the local sky, then
+% we will have an error of XXX.
+% 
+% \note{outline the variation of {\em ApResid} as a function of
+% magnitude}.
+
+%%% \ippprog{psphot} measures the aperture correction ({\em ApResid}) for every PSF
+%%% candidate source, then calculates the trend of this correction as a
+%%% function of the magnitude.  This trend is fitted with a line.  The
+%%% resulting function can be used to determine the effective aperture
+%%% correction for an infinite flux source and the average bias inherent
+%%% in the sky measurement for the image.  The scatter of the
+%%% PSF-candidate source measurements about this trend is a measure of how
+%%% well we can measure photometry from the image by applying the specific
+%%% PSF model.  The slope of this trend is a measure of the bias in the
+%%% local sky measurment for each source.  In principal, the measured sky
+%%% levels could be modified by this bias.  More generally, the measured
+%%% bias in a collection of images could be used to improve the model
+%%% fitting or sky fitting portion of the software the remove the bias
+%%% term.
+
+\ippprog{psphot} allows a collection of PSF model functions to be tried on all
+PSF candidate sources.  For each model test, the above corrected
+ApResid scatter is measured.  The PSF model function with the smallest
+value for the ApResid scatter is then used by \ippprog{psphot} as the best PSF
+model for this image.  The number of models to be tested is specified
+by the configuration keyword \code{PSF_MODEL_N}.  The configuration
+variables \code{PSF_MODEL_0}, \code{PSF_MODEL_1}, through
+\code{PSF_MODEL_N - 1} specify the names of the models which should be
+tested.
+
+\subsection{Stellar Photometry Example}
+
+To illustrate the quality of the stellar photometry as measured with
+PSF and aperture magnitudes, we show the results of an analysis of a
+set of 18 images obtained by PS1 19 February 2010.  These images were
+obtained for the stellar transit survey ``Pan-Planets''
+\citep{2016A&A...587A..49O} and thus target a relatively dense
+Galactic plane field.  The observations were obtained with
+approximately consistent pointing, reducing our sensitivity to
+small-scale variations in the flat-field structures.
+
+Figures~\ref{fig:mag.resid.psf} and ~\ref{fig:mag.resid.aper} show
+comparisons of the PSF and aperture photometry measured for these 18
+images.  In these figures, the photometry has been measured using the
+configuration for \ippprog{psphot} as used for the full PV3
+\ippstage{chip} analysis.  The first image of the sequence is compared
+to the remaining 17 images.  A relative zero point correction is
+applied, measured as the median of the photometry difference for stars
+with signal-to-noise greater than 50.  The combined error is reported
+and used to generate the histograms shows in the figures.  From these
+two figures, one can observe the trade-off between PSF and aperture
+photometry.  For the brightest instrumental magnitudes, corresponding
+to signal-to-noise ratios greater than roughly 300, aperture
+magnitudes provide a more consistent measurement of the stellar
+fluxes, while the PSF magnitudes are more reliable for fainter
+sources.  Catastophic failures or extreme outliers are also reduced
+for the PSF photometry.
+
+We largely attribute the behavior on the bright end to systematic
+errors in the photometry due to our inability to perfectly represent
+the shape of the PSF.  The PSF of stars at the bright end will depend
+on the brightness because of the ``Brighter-Fatter'' effect
+\citep[][]{2014JInst...9C3048A,2015JInst..10C5032G}, in which the
+charge already present in the pixels will force the newly arriving
+photoeletrons to be systematically pushed away from the accumulating
+stellar image, but we do not include a brightness term in our PSF
+model.  Detector or electronic non-linearity may also affect the PSF
+shape and thus the PSF photometry, though non-linearity will affect
+the reported photometry for both PSF and aperture magnitudes.
+
+We believe the observed behavior at the faint end is primarily a
+result of the increased crowding.  Aperture photometry is more
+adversely affected by close neighbors than PSF photometry.  Compared
+to the formal errors, the faint PSF photometry is the most reliable,
+with the aperture photometry degrading rapidly as the flux of the star
+decreases.  
+
+\section{Extended Source Analysis}
+\label{sec:extended.source}
 
 After the initial, fast analysis of the image relying primarily on the
@@ -2013,5 +2235,5 @@
 % if |b| > 20.0 + 15.0 exp(-long^2 / (2 * 50^2))
 
-\subsubsection{Radial Profiles}
+\subsection{Radial Profiles}
 \label{sec:radial.profile.v2}
 
@@ -2082,5 +2304,5 @@
 % \note{these profiles are not saved in PSPS}
 
-\subsubsection{Petrosian Radii and Magnitudes}
+\subsection{Petrosian Radii and Magnitudes}
 \label{sec:petrosian}
 
@@ -2141,5 +2363,5 @@
 
 
-\subsubsection{Convolved Galaxy Model Fits}
+\subsection{Convolved Galaxy Model Fits}
 \label{sec:galaxy.conv.fit}
 
@@ -2347,5 +2569,5 @@
 any of the parameters.
 
-\subsubsection{Fixed Aperture Photometry}
+\subsection{Fixed Aperture Photometry}
 \label{sec:fixed.aperture.photom}
 
@@ -2397,141 +2619,85 @@
 % last bin is first with inner radius >= skyRadius
 
-\subsection{Aperture Correction and Total Aperture Fluxes}
-\label{sec:aperture.correction}
-
-A PSF model will always fail to describe the flux of the stellar
-sources at some level.  For high-precision photometry, we need to be
-able to correct for the difference between the PSF model fluxes and
-the total flux of the sources.  In the end, all astronomical
-photometry is in some sense a relative measurement between two images.
-Whether the goal is calibration of a science image taken at one
-location to a standard star image at another location, or the goal is
-simply the repetitive photometry of the same star at the same location
-in the image, it is always necessary to compare the photometry between
-two images.  If this measurement is to be consistent, then the
-measurement must represent the flux of the stars in the same way
-regardless of the conditions under which the images were taken, at
-least within some range of normal image conditions.  So, for example,
-two images with different image quality, or with different tracking
-and focus errors, will have different PSF models.  To the extent the
-PSF model is inaccurate, the measured flux of the same source in the
-two images will be different (even assuming all other atmospheric and
-instrumental effects have been corrected).  The amplitude of the error
-will by determined by how inconsistently the models represent the
-actual source flux.
-
-Aperture photometry attempts to avoid these problems, but introduces
-other difficulties.  In aperture photometry, if a large enough
-aperture is chosen, the amount of flux which is lost will be a small
-fraction of the total source flux.  Even more importantly, as the
-image conditions change, the amount lost will change by an even
-smaller fraction, at least for a large aperture.  This can be seen by
-the fact that the dominant variations in the image quality are in the
-focus, tracking and seeing.  All of these errors initially affect the
-cores of the stellar images, rather than the wide wings.  The wide
-wings are largely dominated by scattering in the optics and scattering
-in the atmosphere.  The amplitude and distribution of these two
-scattering functions do not change significantly or quickly for a
-single telescope and site.  Aperture photometry can then be used to
-correct the PSF photometry.
-
-The difficulty for aperture photometry is the need to make an accurate
-measurement of the local background for each source.  As the aperture
-grows, errors in the measurement of the sky flux start to become
-dominant.  If the aperture is too small, then variations in the image
-quality are dominant.  The brighter is the source, the smaller is the
-error introduced by the large size of the aperture.  However, the
-number of very bright stars is limited in any image, and of course the
-brighter stars are more likely to suffer from non-linearity or
-saturation.  
-
-In order to thread the needle between these effects, \ippprog{psphot}
-measures the aperture photometry on a modest-sized aperture, and then
-uses the PSF model to extrapolate to a large aperture.  When the PSF
-fluxes are calculated, the aperture flux for the modest-sized aperture
-is also determined.  The aperture is a circular aperture with radius
-set to a fixed multiple (\code{PSF_APERTURE_SCALE}) of $\sigma_w$, the
-width of the Gaussian window function determined based on the analysis
-of the second moments (see Section~\ref{sec:moments}).  For the PV3
-$3\pi$ analysis, the aperture window radius is $4.5 \times \sigma_w$,
-while the large reference aperture radius is set to 25 pixels
-(\code{PSF_REF_RADIUS} = 6\farcs4).  These corrected aperture
-magnitudes are saved in the output catalogs as \code{AP_MAG}, the
-uncorrected aperture magnitudes are saved as \code{AP_MAG_RAW}, and
-the radius used to measure the raw aperture flux is saved as
-\code{AP_MAG_RADIUS}.  The corresponding flux and the flux error are
-saved as \code{AP_FLUX} and \code{AP_FLUX_SIG}.
-
-With these aperture magnitudes in hand, it is now possible to make an
-average correction to the PSF magnitudes to bring the PSF and aperture
-magnitudes to the same system.  This correction is measured using the
-same stars from which the PSF model is measured, as long as the PSF
-magnitude error for the star is less than 0.03 mag.  The correction is
-calculated using the weighted average of the values $m_{\rm AP} -
-m_{\rm PSF}$.  Since the PSF may vary across the image, the correction
-is determined as a function of position in the image.  Like the PSF
-model, the 2D variations of the aperture correction may be modeled as
-a polynomial or via interpolation in a grid.  For the $3\pi$ PV3
-analysis, a grid with a maximum of $6\times 6$ samples per GPC1 chip
-image was used.  The reported PSF magnitudes for all objects have this
-aperture correction applied.
-
-% growth curve analysis in psphot:
-% in psphotChoosePSF : call psphotMakeGrowthCurve
-% in psphotMakeGrowthCurve : boolean GROWTH_FROM_SOURCES, use
-%% pmGrowthCurveGenerateFromSources or
-%% pmGrowthCurveGenerate (uses PSF model only)
-%% GROWTH_FROM_SOURCES is set to TRUE for default recipe
-
-%% ApTrend:
-%% in psphotApResid, called by psphotReadout near the end of the
-%% analysis
-%% ApTrend = f(x,y) for (apMag - psfMag) for psfMagErr <= 0.03
-%% apMag is growth curve corrected
-%% psfMag is raw
-
-%% raw psfMag and raw apMag are measured
-%% apMag = apMagRaw + growth curve correction (from apRadius to 25 pix
-%% = PSF_REF_RADIUS)
-%% psfMag = psfMagRaw + aperture trend (<ap - psf> + growth curve)
-
-% How important is this effect?  Consider a typical bright source with a
-% flux of (say) 40,000 counts in an image of background 1000 counts per
-% pixel, with FWHM of 4 pixels.  In principle, the flux of this source
-% should be measurable with an accuracy of roughly 0.57\%
-% ($\frac{\sqrt{40000 + 1000 \times 12}}{40000}$).  However, the
-% measurement of the sky is limited at some finite level by Poisson
-% statistics.  If we are required to use an aperture of (say) 25 pixels
-% in radius (eg, 5 arcseconds for an 0.2 arcsec / pixel detector), and
-% we have an annulus of twice this radius to measure the local sky, then
-% we will have an error of XXX.
-% 
-% \note{outline the variation of {\em ApResid} as a function of
-% magnitude}.
-
-%%% \ippprog{psphot} measures the aperture correction ({\em ApResid}) for every PSF
-%%% candidate source, then calculates the trend of this correction as a
-%%% function of the magnitude.  This trend is fitted with a line.  The
-%%% resulting function can be used to determine the effective aperture
-%%% correction for an infinite flux source and the average bias inherent
-%%% in the sky measurement for the image.  The scatter of the
-%%% PSF-candidate source measurements about this trend is a measure of how
-%%% well we can measure photometry from the image by applying the specific
-%%% PSF model.  The slope of this trend is a measure of the bias in the
-%%% local sky measurment for each source.  In principal, the measured sky
-%%% levels could be modified by this bias.  More generally, the measured
-%%% bias in a collection of images could be used to improve the model
-%%% fitting or sky fitting portion of the software the remove the bias
-%%% term.
-
-\ippprog{psphot} allows a collection of PSF model functions to be tried on all
-PSF candidate sources.  For each model test, the above corrected
-ApResid scatter is measured.  The PSF model function with the smallest
-value for the ApResid scatter is then used by \ippprog{psphot} as the best PSF
-model for this image.  The number of models to be tested is specified
-by the configuration keyword \code{PSF_MODEL_N}.  The configuration
-variables \code{PSF_MODEL_0}, \code{PSF_MODEL_1}, through
-\code{PSF_MODEL_N - 1} specify the names of the models which should be
-tested.
+\subsection{Galaxy Model Simulations}
+
+To test the galaxy model analysis, we have generated a series of
+simulated images containing both stars and galaxies on which we have
+run the \ippprog{psphot} PSF-convolved galaxy model fitting analysis.
+The images generated for this analysis have dimensions of $4000 \times
+4000$ pixels with a spatial scale of 0.25 arcseconds per pixel.  The
+images are generated using an effective exposure time of 30 seconds,
+with zero points matching the PS1 \rps-filter, and a realistic sky
+brightness of 20.86 magnitudes per square arcsecond.  The stars are
+injected into these images with fluxes drawn from a realistic stellar
+luminosity function and random spatial locations.  For each image, the
+same underlying simulated stellar population was used.  Galaxies are
+injected into the image with positions on a regularly spaced grid with
+separation of 120 pixels.  The galaxies are injected using Exponential
+and DeVaucouleur profiles in separate simulation runs.  The major axis
+values are randomly distributed between 1 and 10 pixels (0.25 - 2.5
+arcseconds) while the aspect ratios are randomly chosen in a range
+from 0.25 to 1.0.  The position angles are set by the sequence in the
+image and allowed to vary from 0 to 180 degrees.  The images are then
+convolved with a PSF model using the \code{PS1_V1} profile ($\kappa =
+0.2$) and noise is added using Poisson statistics for the detected photons.
+
+For the figures below, we present results as a function of the (input)
+instrumental magnitude of the galaxy minus the instrumental magnitude
+corresponding to the stellar $5 \sigma$ detection limit.  We make the
+simplifying assumption that the stellar detection threshold
+encapsulates enough information about the sensitivity of the images
+that this magnitude difference may be used to compare the results
+shown here to images with other depths.  Thus this and subsequent
+figures may be compared with the reported detection limits from the
+PS1 $3\pi$ survey.  Note for reference that the typical stellar
+detection limits in the PS1 $3\pi$ stack images are (\grizy) = (23.3,
+23.2, 23.1, 22.3, 21.4).  The minimum Kron magnitudes for which galaxy
+model fits were performed for the PV3 analysis
+(Section~\ref{sec:extended.source}) thus correspond to -1.6 to -1.8 in
+these plots.
+
+Figure~\ref{fig:galaxy.complete} shows completeness for the detection
+of the Exponential and DeVaucouleur model galaxies.  This analysis
+does not indicate if the galaxy was detected {\em as a galaxy} (\ie,
+was the extended nature of the source sufficiently clear), only if
+the source was detected by the peak-finding algorithm.  As expected,
+the more compact galaxies are more likely to be detected; Exponential
+profile galaxies, with a broader light distribution for the same
+effective radius, are less likely to be detected for the same
+magnitude than DeVaucouleur profile galaxies.
+
+\begin{figure}[htbp]
+  \begin{center}
+ \includegraphics[width=\hsize,clip]{pics/{galaxy.exp.complete}.png}
+ \includegraphics[width=\hsize,clip]{pics/{galaxy.dev.complete}.png}
+  \caption{\label{fig:galaxy.complete} Top: Completeness curves for
+    simulated galaxies with Exponential profiles.  Bottom:
+    Completeness curves for simulated galaxies with DeVaucouleur
+    profiles.  The curves are shown as a function of the difference
+    between the injected instrumental magnitude of the galaxy and the
+    magnitude corresponding to the $5\sigma$ detection threshold for a
+    PSF-like source.  The black curves shows the compleness for all
+    galaxies.  The three colored curves show the completeness for
+    three major axis ranges. Compact galaxies are more likely to be
+    detected since peaks are detected after convolution with the
+    PSF. }
+  \end{center}
+\end{figure}
+
+\begin{figure*}[htbp]
+  \begin{center}
+ \includegraphics[width=\hsize,clip]{pics/{galaxy.exp.params}.png}
+  \caption{\label{fig:exp.complete} Parameter recovery for simulated
+    galaxies with Exponential profiles.  }
+  \end{center}
+\end{figure*}
+
+\begin{figure*}[htbp]
+  \begin{center}
+ \includegraphics[width=\hsize,clip]{pics/{galaxy.dev.params}.png}
+  \caption{\label{fig:dev.complete} Parameter recovery for simulated
+    galaxies with DeVaucouleur profiles.  }
+  \end{center}
+\end{figure*}
 
 \section{Forced Photometry Modes}
@@ -2679,13 +2845,4 @@
 \label{sec:lensing.params}
 
-\begin{verbatim}
-* background : KSB, related (mention Deacon et al here or at the end?)
-* second moments are discussed above (same values, including window function as given)
-* write out the KSB formalism
-* stellar parameters using PSF stars
-* output parameters
-* this is only done on warp -- move to ForceWarp section?
-\end {verbatim}
-
 Weak-lensing studies frequently use non-parametric measurements of the
 ellipticities of galaxies to quantify the strength of gravitational
@@ -2706,23 +2863,28 @@
 applied the techinique to PTF data to search for binary stars and
 \cite{2017MNRAS.468.3499D} used the same technique to search for
-binary companions to known ultracool dwarfs using Pan-STARRS $\3pi$
+binary companions to known ultracool dwarfs using Pan-STARRS $3\pi$
 data.  The work by \cite{2017MNRAS.468.3499D} used images and their
 own analysis of the pixels with the program Sextractor
 \citep{Bertin.ref}.
 
-For the Pan-STARRS $\3pi$ PV3 analysis, we have measured the full set
-of KSB lensing parameters for \note{which subset?} of the data to
-enable both lensing studies and binary / multiple star searches.  Here
-we describe the measurements as performed within \ippprog{psphot},
-reviewing the mathematical framework as described by
-\cite{1995ApJ...449..460K} and \cite{1998ApJ...504..636H}.
+For the Pan-STARRS $3\pi$ PV3 analysis, we have measured the full set
+of KSB lensing parameters for all objects with measured second moments
+(i.e.,, excluding saturated stars, suspected cosmic rays, and other
+likely defects) of the data to enable both lensing studies and binary
+/ multiple star searches.  Here we describe the measurements as
+performed within \ippprog{psphot}, reviewing the mathematical
+framework as described by \cite{1995ApJ...449..460K} and
+\cite{1998ApJ...504..636H}.
 
 The goal of the KSB technique is to measure the intrinsic ellipticity
 of objects (i.e., galaxies, in the case of weak lensing studies) as
-would be observed sky on the without instrumental effects.  The
-analysis starts with the observed ellipticity of the object as
-represented by the two polarization components derived from the second
-moments (see Section~\ref{sec:moments}):
+would be observed sky on the without instrumental effects and to
+determine the impact weak graviational lensing would have on the
+observed shapes, after correction for the instrumental effects.  The
+analysis starts with the observed ellipticity of objects as represented
+by the two polarization components derived from the second moments
+(see Section~\ref{sec:moments}):
 \begin{eqnarray}
+\label{eqn:polarization}
   e_1 = \frac{M_{xx} - M_{yy}}{M_{xx} + M_{yy}} \\
   e_2 = \frac{2 M_{xy}}{M_{xx} + M_{yy}}. \\
@@ -2738,124 +2900,129 @@
 $e_2$ and low absoluate values of $e_1$.
 
-\note{need for the window function}.
-
-The observed ellipticity of an object observed in a real instrument
+Note that in our analysis of the second moments, we are applying a
+Gaussian window function to down-weight the noise contributions from
+pixels at high radii and low flux (see Section~\ref{sec:moments}).
+This type of window function is also assumed in the KSB formalism, and
+is represented in the equations below as $W$.
+
+The measured ellipticity of an object observed in a real instrument
 will be affected by the point spread function of the instrument.  To
 first order, the effect on the polarization components can be
-described as a combination of ``smear'', in which the observed shape
-is more circularized (driving $e_1,e_2$ to low absolute values) and
-``shear'', in which the observed shape is stretched in one direction
+described as a combination of the circularly symmetric seeing disc,
+which smears the observed shapes (driving $e_1,e_2$ to low absolute
+values) and the shearing effect of the anisotropic component of the
+PSF, in which the observed shape is stretched in one direction
 relative to the others (driving $e_1,e_2$ to larger absolute values).
-With sufficient understanding of the image PSF, both shear and smear
-terms can be corrected.  
-
-The change in the observed polarization of an object due to the 
-
+
+KSB and HFK quantify the change in the observed polarization due to
+the smearing effect of the PSF with
+\begin{equation}
+  \delta e^{\rm sm}_\alpha = P^{\rm sm}_{\alpha, \beta} p_{\beta}
+\end{equation}
+$p_\beta$ is a measurement of the
+anisotropy of the PSF (see below), and $P^{\rm sm}_{\alpha,\beta}$ is
+the ``Smear Polarizability'' of the object, defined as  
 \begin{eqnarray}
-X^{sh}_{1,1} = T^{-1} \sum f \left[ 2W(x^2 + y^2) + 2W^\prime (x^2 - y^2)^2 \\
-X^{sh}_{1,2} = T^{-1} \sum f \left[ 4W^\prime(x^2 - y^2) x y \\
-X^{sh}_{2,2} = T^{-1} \sum f \left[ 2W(x^2 + y^2) + 8W^\prime x^2 y^2 \\
+  P^{\rm sm}_{\alpha \beta} = X^{\rm sm}_{\alpha \beta} - e_\alpha e^{\rm sm}_\beta
+\end{eqnarray}  
+where 
+\begin{eqnarray}
+X^{\rm sm}_{1,1} &=& \frac{1}{T} \sum f \left[ W + 2W^\prime r^2 + W^{\prime \prime} (x^2 - y^2)^2 \right] \\
+X^{\rm sm}_{1,2} &=& \frac{1}{T} \sum f \left[ 2W^{\prime\prime} (x^2 - y^2) x y \right] \\
+X^{\rm sm}_{2,2} &=& \frac{1}{T} \sum f \left[ W + 2W^\prime r^2 + 4W^{\prime \prime} x^2 y^2 \right]
 \end{eqnarray}
-
+and  
 \begin{eqnarray}
-e^{sh}_1 = 2 e_1 + 2 T^{-1} \sum f W^\prime (x^2 + y^2) (x^2 - y^2) \\
-e^{sh}_2 = 2 e_2 + 2 T^{-1} \sum f W^\prime (x^2 + y^2) 2 x y \\
+e^{\rm sm}_1 &=& \frac{1}{T} \sum f \left[ 2W^\prime + W^{\prime \prime} (x^2 + y^2) \right] (x^2 - y^2) \\
+e^{\rm sm}_2 &=& \frac{1}{T} \sum f \left[ 2W^\prime + W^{\prime \prime} (x^2 + y^2) \right] 2 x y.
 \end{eqnarray}
-
+In these equations, $T = M_{xx} + M_{yy}$ and $W$ is the window
+function applied when measuring the second moments.  The terms
+$W^\prime$ and $W^{\prime \prime}$ are the derivatives of the window
+function with respect to $r^2 = x^2 + y^2$.  Since the window function
+is a circularly-symmetric Gaussian with width $\sigma_w$, the
+derivatives are simply $W^\prime = -\frac{1}{2\sigma^2_w} W$ and
+$W^{\prime \prime} = \frac{1}{4\sigma^4_w} W$.
+
+The elements of the equations above can be written in terms of the second and higher-order
+moments calculated in Section~\ref{sec:moments}:
 \begin{eqnarray}
-X^{sm}_{1,1} = T^{-1} \sum f \left[ W + 2W^\prime (x^2 + y^2) + W^{\prime \prime} (x^2 - y^2)^2 \\
-X^{sm}_{1,2} = T^{-1} \sum f \left[ 2W^{\prime\prime} (x^2 - y^2) x y \\
-X^{sm}_{2,2} = T^{-1} \sum f \left[ W + 2W^\prime (x^2 + y^2) + 4W^{\prime \prime} x^2 y^2 \\
+X^{\rm sm}_{1,1} &=& \frac{1}{T} \left[ 1 - \frac{R_2}{\sigma^{2}} + \frac{(M_{xxxx} - 2 M_{xxyy} + M_{yyyy})}{4 \sigma^{4}} \right] \\[0.1in]
+X^{\rm sm}_{1,2} &=& \frac{1}{T} \left[ \frac{(M_{xyyy} - M_{xxxy})}{2 \sigma^{4}} \right] \\[0.1in]
+X^{\rm sm}_{2,2} &=& \frac{1}{T} \left[ 1 - \frac{R_2}{\sigma^{2}} + \frac{ M_{xxyy}}{\sigma^{4}} \right]
 \end{eqnarray}
-  
+and  
 \begin{eqnarray}
-e^{sm}_1 = T^{-1} \sum f \left[ 2W^\prime + W^{\prime \prime} (x^2 + y^2) \right] (x^2 - y^2) \\
-e^{sm}_2 = T^{-1} \sum f \left[ 2W^\prime + W^{\prime \prime} (x^2 + y^2) \right] 2 x y \\
+e^{\rm sm}_1 &=& \frac{1}{T} \left[ \frac{M_{xx} - M_{yy}}{\sigma^{2}} + \frac{M_{xxxx} - M_{yyyy}}{4 \sigma^{4}} \right] \\[0.1in]
+e^{\rm sm}_2 &=& \frac{1}{T} \left[ \frac{(M_{xxxy} + M_{xyyy})}{2\sigma^{4}} - \frac{2 M_{xy}}{\sigma^{2}} \right]
 \end{eqnarray}
-  
-
-@ARTICLE{2017MNRAS.468.3499D,
-   author = {{Deacon}, N.~R. and {Magnier}, E.~A. and {Best}, W.~M.~J. and 
-	{Liu}, M.~C. and {Dupuy}, T.~J. and {Chambers}, K.~C. and {Draper}, P.~W. and 
-	{Flewelling}, H. and {Metcalfe}, N. and {Tonry}, J.~L. and {Wainscoat}, R.~J. and 
-	{Waters}, C.},
-    title = "{Identification of partially resolved binaries in Pan-STARRS 1 data}",
-  journal = {\mnras},
-archivePrefix = "arXiv",
-   eprint = {1702.05491},
- primaryClass = "astro-ph.SR",
- keywords = {binaries: visual, brown dwarfs},
-     year = 2017,
-    month = jul,
-   volume = 468,
-    pages = {3499-3515},
-      doi = {10.1093/mnras/stx440},
-   adsurl = {http://adsabs.harvard.edu/abs/2017MNRAS.468.3499D},
-  adsnote = {Provided by the SAO/NASA Astrophysics Data System}
-}
-
-@ARTICLE{1995ApJ...449..460K,
-   author = {{Kaiser}, N. and {Squires}, G. and {Broadhurst}, T.},
-    title = "{A Method for Weak Lensing Observations}",
-  journal = {\apj},
-   eprint = {astro-ph/9411005},
- keywords = {COSMOLOGY: OBSERVATIONS, COSMOLOGY: DARK MATTER, GALAXIES: FORMATION, COSMOLOGY: GRAVITATIONAL LENSING, COSMOLOGY: LARGE-SCALE STRUCTURE OF UNIVERSE},
-     year = 1995,
-    month = aug,
-   volume = 449,
-    pages = {460},
-      doi = {10.1086/176071},
-   adsurl = {http://adsabs.harvard.edu/abs/1995ApJ...449..460K},
-  adsnote = {Provided by the SAO/NASA Astrophysics Data System}
-}
-@ARTICLE{1998ApJ...504..636H,
-   author = {{Hoekstra}, H. and {Franx}, M. and {Kuijken}, K. and {Squires}, G.
-	},
-    title = "{Weak Lensing Analysis of CL 1358+62 Using Hubble Space Telescope Observations}",
-  journal = {\apj},
- keywords = {GALAXIES: CLUSTERS: INDIVIDUAL ALPHANUMERIC: CL 1358+62, GALAXIES: FUNDAMENTAL PARAMETERS, COSMOLOGY: GRAVITATIONAL LENSING, galaxies: clusters: individual (Cl 1358 + 62), Galaxies: Fundamental Parameters, Cosmology: Gravitational Lensing},
-     year = 1998,
-    month = sep,
-   volume = 504,
-    pages = {636-660},
-      doi = {10.1086/306102},
-   adsurl = {http://adsabs.harvard.edu/abs/1998ApJ...504..636H},
-  adsnote = {Provided by the SAO/NASA Astrophysics Data System}
-}
-@ARTICLE{2005ApJ...626.1070H,
-   author = {{Hoekstra}, H. and {Wu}, Y. and {Udalski}, A.},
-    title = "{An Algorithm to Detect Blends with Eclipsing Binaries in Planet Transit Searches}",
-  journal = {\apj},
-   eprint = {astro-ph/0501353},
- keywords = {Stars: Binaries: Eclipsing, Stars: Planetary Systems},
-     year = 2005,
-    month = jun,
-   volume = 626,
-    pages = {1070-1078},
-      doi = {10.1086/430299},
-   adsurl = {http://adsabs.harvard.edu/abs/2005ApJ...626.1070H},
-  adsnote = {Provided by the SAO/NASA Astrophysics Data System}
-}
-@ARTICLE{2013ApJS..206...18T,
-   author = {{Terziev}, E. and {Law}, N.~M. and {Arcavi}, I. and {Baranec}, C. and 
-	{Bloom}, J.~S. and {Bui}, K. and {Burse}, M.~P. and {Chorida}, P. and 
-	{Das}, H.~K. and {Dekany}, R.~G. and {Kraus}, A.~L. and {Kulkarni}, S.~R. and 
-	{Nugent}, P. and {Ofek}, E.~O. and {Punnadi}, S. and {Ramaprakash}, A.~N. and 
-	{Riddle}, R. and {Sullivan}, M. and {Tendulkar}, S.~P.},
-    title = "{Millions of Multiples: Detecting and Characterizing Close-separation Binary Systems in Synoptic Sky Surveys}",
-  journal = {\apjs},
-archivePrefix = "arXiv",
-   eprint = {1210.4550},
- primaryClass = "astro-ph.SR",
- keywords = {binaries: close, methods: data analysis, stars: statistics, surveys, techniques: image processing },
-     year = 2013,
-    month = jun,
-   volume = 206,
-      eid = {18},
-    pages = {18},
-      doi = {10.1088/0067-0049/206/2/18},
-   adsurl = {http://adsabs.harvard.edu/abs/2013ApJS..206...18T},
-  adsnote = {Provided by the SAO/NASA Astrophysics Data System}
-}
+where $R_2 = M_{xx} + M_{yy}$.
+
+KSB and HFK use the observed ellipticities of stars and the smear
+polarizability of the stars to estimate the anisotropy due to the PSF:
+\begin{eqnarray}
+p_\alpha = \frac{e^*_{\alpha}}{P^{{\rm sm},*}_{\alpha \alpha}}
+\end{eqnarray}
+where the terms with the $*$ represent parameters measured on stars.
+
+%% \begin{eqnarray}
+%%   p_1 &=& M_{xx} - M_{yy} \\
+%%   p_2 &=& 2 M_{xy}
+%% \end{eqnarray}
+
+Similarly, the impact of shear can be quantified by the ``Shear
+Polarizabilty'' in a similar fashion:
+\begin{equation}
+  \delta e^{\rm sh}_\alpha = P^{\rm sh}_{\alpha, \beta} p_{\beta}
+\end{equation}
+where now the shear polarizability $P^{\rm sh}_{\alpha \beta}$ is
+defined as
+\begin{eqnarray}
+  P^{\rm sh}_{\alpha \beta} = X^{\rm sh}_{\alpha \beta} - e_\alpha e^{\rm sh}_\beta
+\end{eqnarray}  
+where
+\begin{eqnarray}
+X^{\rm sh}_{1,1} &=& \frac{1}{T} \sum f \left[ 2W(x^2 + y^2) + 2W^\prime (x^2 - y^2)^2 \right] \\
+X^{\rm sh}_{1,2} &=& \frac{1}{T} \sum f \left[ 4W^\prime(x^2 - y^2) x y \right] \\
+X^{\rm sh}_{2,2} &=& \frac{1}{T} \sum f \left[ 2W(x^2 + y^2) + 8W^\prime x^2 y^2 \right]
+\end{eqnarray}
+and
+\begin{eqnarray}
+e^{\rm sh}_1 &=& 2 e_1 + \frac{2}{T} \sum f W^\prime (x^2 + y^2) (x^2 - y^2) \\
+e^{\rm sh}_2 &=& 2 e_2 + \frac{2}{T} \sum f W^\prime (x^2 + y^2) 2 x y.
+\end{eqnarray}
+
+Re-writing in terms of the second and higher-order moments calculated
+in Section~\ref{sec:moments}, we find:
+\begin{eqnarray}
+X^{\rm sh}_{1,1} &=& \frac{1}{T} \left[ 2 R_2 - \frac{(M_{xxxx} - 2 M_{xxyy} + M_{yyyy})}{\sigma^{2}} \right] \\
+X^{\rm sh}_{1,2} &=& \frac{1}{T} \left[ \frac{2(M_{xyyy} - M_{xxxy})}{\sigma^{2}} \right] \\
+X^{\rm sh}_{2,2} &=& \frac{1}{T} \left[ 2 R_2 - \frac{4 M_{xxyy}}{\sigma^{2}} \right]
+\end{eqnarray}
+and  
+\begin{eqnarray}
+e^{\rm sh}_1 &=& \frac{1}{T} \left[ 2 (M_{xx} - M_{yy}) + \frac{( M_{yyyy} - M_{xxxx})}{\sigma^{2}} \right] \\
+e^{\rm sh}_2 &=& \frac{1}{T} \left[ 4 M_{xy} - \frac{2 (M_{xxxy} + M_{xyyy})}{\sigma^{2}} \right] 
+\end{eqnarray}
+
+In the Pan-STARRS PV3 analysis, we have measured the elements of the
+smear polarizability ($X^{\rm sm}_{\alpha \beta}$, $e^{\rm
+  sm}_\alpha$) and the shear polarizability ($X^{\rm sh}_{\alpha
+  \beta}$, $e^{\rm sh}_\alpha$) for all objects on each of the warp
+images.  We have also selected only the PSF stars from the images and
+interpolated a smoothed version of these parameters to the location of
+the objects, using the grid described above to interpolate the PSF
+parameters.  We also determine the interpolated PSF ellipticities
+($e^*_1, e^*_2$) from the equivalent smooth grid.  Thus, for every
+object in the $3\pi$ survey, we are able to report the PSF and object
+elements of the KSB analysis.  These lensing parameters are measured
+for each of the warps, and then averaged over all warps for each of
+the filters.  The average values are calculated by including only
+measurements from the same warp detection used in the average
+photometry (nominally, the primary skycell; see Paper V, Section
+5.4.4) and excluding any measurements for which the \code{PSF_QF} or
+\code{PSF_QF_PERFECT} is less than 0.85.
+
+\note{example of using the lensing elements for binaries?}
 
 \section{Difference Image Photometry}
