By Larry Weber and Steve Brady
Focusing CCD-based telescopes is one of the drudgeries astronomers constantly face. With the recent advent of relatively low cost, motorized position-feedback focusing hardware, comes an opportunity to fully automate the focusing operation. This paper presents a new method and software for automatically focusing CCD based telescope systems. It is highly suitable for unattended all-night robotic-telescope operations such as asteroid searches, astrometry, photometry, imaging, etc. The only requirements are a CCD based telescope, a commercially available position-feedback motorized-focuser  and CCD camera control software .
Automated focusing systems demand solution to a wide range of challenging technical problems and specifications. Ideally, any automated focus method should:
To facilitate full automation, the software should have a standard ASCOM interface  that allows the user to write simple scripts that can coordinate the focusing operation with the other telescope operations. Ideally this means that once the system and software are properly configured, then the user only needs to press one focus button to initiate a successful focus operation. We believe our method and software meets all of these requirements.
To meet the above requirements an accurate and robust focus metric is needed. Traditionally, astronomers have used a number of techniques to characterize the Point Spread Function (PSF) of a star. One common method is a gaussian function fit to the PSF. Unfortunately, severely out of focus stars frequently have the shape of an annulus or disk, which does not match the shape of the gaussian accurately. We have found the Full Width Half Maximum (FWHM) metric used to quantify the width of the star PSF to work most of the time but not with sufficient accuracy for auto-focusing. This is due to variations in seeing which cause local peaks in the unfocused star PSF and severely degrades the calculation of the maximum when assessing the FWHM.
We have based our auto-focus algorithm on a metric named the Half Flux Diameter (HFD). The HFD is defined as the diameter of a circle that is centered on the unfocused star image in which half of the total star flux is inside the circle and half is outside. The HFD gives a single number, in units of CCD pixels, that is relatively insensitive to variations in seeing, star flux, thin clouds or sky background glow. We have found this one metric to be accurate over a very wide range of unfocused star diameters and flux intensities because the HFD is determined by integrating all of the flux from the unfocused star area. HFD does not suffer from the problems found with gaussian fits or FWHM.
Note that in our earlier version of this paper,  we defined our degree of focus metric as a Half Flux Radius (HFR). The HFD metric has exactly the same concept as the HFR metric with the obvious identity:
HFD = 2 * HFR.
We have adopted HFD, at the recommendation of Douglas B. George. This is for user convenience since, for small star disks, the measured HFD value is quite similar to the more familiar FWHM of the star.
A Plot of the measured HFD vs. the precision focus position gives a very stable V shaped curve where the Best Focus Position is at the apex of the V. The sample to the left shows actual data that was automatically measured on an 8 inch LX-200, ST-8E system during good seeing conditions near sea level. The horizontal axis is the focuser position and the vertical axis is the HFD. This V Curve is an accurate quantitative measure of the telescope optical convergence cone and beam waist. The measured left and right sides of the V Curve are delightfully linear with slopes that depend only on the hardware characteristics such as the optics f-number, the CCD pixel size and the focuser gear ratios. We have found these slopes to be remarkably constant over temperature and time.
The software automatically fits straight lines to the data between the user specified high and low HFD limits. It also measures the straight-line slopes, position intercepts and the position intercept difference (shown in the lower section). The telescope-CCD-focuser system can be completely characterized by measuring the three parameters, the Left Slope, the Right Slope and the Position Intercept Difference. Once the system is characterized with accurate values for these three parameters, the best focus position can be predicted from a well-sampled HFD measurement at a known position and the additional knowledge of which side of Best Focus the system is on. Note, the value of the Position at Best Focus shown is only of transient interest and is not useful for characterizing the system.
To begin, the user must characterize the telescope-CCD-focuser system by automatically measuring the V Curve and extracting the three parameters. In principle, the Best Focus Position can be determined with a measured target star HFD, the position of the focuser and knowledge of which side of Best Focus the focuser is on. In practice more than one HFD measurement is made and the results are averaged to increase the signal to noise ratio making the Best Focus determination more accurate.
We have written a user-friendly MS Windows application to automatically focus the telescope. In a typical run the telescope can be routinely brought to focus in only one minute with a LX-200, ST-8E system. The process is:
This technique allows accurate determination of the best focus position by moving the focuser in one direction which eliminates issues such as backlash and mirror flop, which are found on many telescope focus mechanisms.
This strategy determines Best Focus based on the HFD of the one brightest star on the CCD. We have found this one star strategy to be valuable since this star can be centered on the CCD chip to reduce the influence of off axis optical aberrations such as field curvature and coma. With robotic telescope operation, it is relatively easy to find a sufficiently bright star for this strategy. We also allow the user to manually select a single target star in a crowded star field.
Currently, the gating time factor in the auto-focus process is the slow download time of the CCD and not exposure time. We have found that if a target star is selected in the 1st to 7th magnitude range, exposure times for can be kept very short and still achieve equal or better performance than longer exposures. For the ST-8E camera we typically use the minimum 0.11 sec and have good results with the faster 0.05 sec shutter speeds of the Apogee AM16 camera. Depending on the users optical system, camera, etc. dimmer stars can be used with the exposure time adjusted accordingly.
This HFD Focus method can be best illustrated by walking through a typical exposure sequence. The first step is to take a full frame 3X3 binned exposure in order to initially find the brightest star. The image from this exposure is shown below.
After the full frame exposure is made, the software finds the brightest star on the chip, frames the target star, subtracts the background level and then measures the HFD.
The main user form that is active while the focusing operation proceeds allows the operator to easily monitor the quality of the focus process. The largest plot on this form is a vertical bin of the framed region centered on the star. The vertical lines to the left and right of the vertical bin curve specify the boundaries of the star detected by the algorithm. The regions outside of the boundaries are used to determine the background level of the image, which is subtracted from the image before the vertical bin curve is plotted.
The small box in the lower left corner shows the location of the target star on the CCD chip. Note that this directly corresponds to the location of the star on the full frame image shown above. Ideally the measured star is near the center of the CCD chip so that off axis aberrations are minimized. This star locator is useful for verifying centering since most of the exposures have very small frame sizes.
For each exposure taken, the Half Flux Diameter is determined which is used for setting the next focus position and frame size.
In this sequence, the new focuser position is set to 9087 and a new exposure taken. Note that the star size is considerably smaller and that the exposure frame size has been reduced to fit the star based on the HFD of the previous exposure. Also, the target star HFD is considerably less than the value measured above. This was by design since the value of 9087 was calculated based on the results of the previous exposure.
The formula used to calculate the new position is:
NP = OP + (NewHFD - OldHFD) / Slope,
Where: NP is the new position,
OP is the old position,
NewHFD is the desired new HFD,
OldHFD is the measured HFD at the old position
Slope is the V Curve slope on the side of focus we are operating.
This formula is simply the equation for a straight line that fits the appropriate side of the V Curve.
When the measured HFD of the initial exposure is large, the focuser position is adjusted so that the next exposure will give approximately one half the quantity: original HFD minus the Near Focus HFD (defined below). So in the example just above, we went from HFD = 24.82 to HFD = 17.41. This half step algorithm is used to insure that severely out of focus stars will properly converge, in spite of system problems such as mirror flop.
The Near Focus HFD is a user specified value that should be set close to the Best Focus position but still on the linear part of the V Curve. In the example presented here the Near Focus HFD is set to10.
When the measured HFD is determined to be within a factor of two of the Near Focus HFD, then the Near Focus HFD position is calculated and the focuser moves to that position. In this example, the position of 9087 gave a HFD of 17.41, which is within a factor of 2 of the Near Focus HFD of 10. The Near Focus HFD position of 9153 was calculated and was found to have an HFD value of 10.01.
At the Near Focus Position, multiple sub-frames are taken (5), and the average HFD value determined. Telescope tracking errors may cause the star to move out of the exposure sub-frame window because the sub-frame size is small. This is corrected by determining the target star centroid following each exposure and positioning the next sub-frame on that position.
The average HFD value is used to determine the final Best Focus position (9240). The focuser is moved to the Best Focus position and a final exposure is taken with the target star HFD measured.
Our software maintains a running Log of all operations with a time stamp for each line, which is useful for monitoring operations and for debugging scripted robotic operations. In the example log shown, at time:
20:56:57 the Focus button was clicked and RoboFocus was commanded to go to the initial position of 9021. After arriving at the position it starts the full chip 3x3 binned exposure.
20:57:24 the exposure was completed and the HFD is measured to be 26.3076 with a total star flux of 14309.
20:57:32 a smaller sub-frame is taken and the HFD value used to calculate the Near Focus position 9166.
20:57:37 Near Focus Exposures begin (5 taken).
20:57:48 Best Focus Position was determined to be 9253.
20:57:54 RoboFocus moves to the Best Focus position and a final exposure taken yielding an HFD of 2.9019
20:57:54 the focusing operation was completed. Total time = 57 seconds!
The auto focusing runs shown on the above running Log were conducted in conditions of variable thin clouds. The column at the far right of this log shows the total star flux; note that during the last run, the flux varies from a high of 14309 to a low of 4607. The focus was successful in spite of more than a 3x factor in flux variation due to thin clouds. Note that on the previous auto-focus run, that started shortly before the top line of the log at 20:56:29, the clouds were thinner so that the total star flux went as high as 42509. In spite of this wide variation in total star flux from run to run, both runs arrived at practically the same final positions (9254 and 9253) and final HFD values (2.7680 and 2.9019)!
After a framed star exposure is taken, the HFD measurement algorithm steps are:
1. Subtract the background level from the image
2. Find the centroid of the star by a simple weighted averages method
3. Determine the radius of each pixel from the centroid
4. Sort the pixels in order of increasing radius
5. Generate an integral of the pixel flux along the diameter (= 2 X radius) dimension. This integral is shown on the user form as a small plot to the left of the Find and Focus buttons. This plots the diameter along the horizontal axis and the integrated flux along the vertical axis. The integral shows zero integrated flux at the zero diameter and it shows the full star flux at the largest diameter.
6. Determine the Half Flux Diameter from this integral, which is simply the diameter where the integrated flux is half of the full star flux. This HFD point is marked on the flux integral plots with a vertical line.
This algorithm works very well for stars with large HFD of perhaps 20 or more. However for smaller HFDs the discrete nature of the square pixels introduces a significant error that increases as the HFD gets smaller. This is corrected by first exactly calculating the fractional contribution of pixel flux that is inside the HFD circle for each pixel that intersects the HFD circle. Then an iterative technique is used that makes small adjustments to the circle diameter to converge at the true HFD where half of the total flux is inside the circle and half is outside.
A foundation of our auto focus algorithm is accurate knowledge of the parameters that characterize the system. The three parameters are the V Curve Left Slope, Right Slope and the Position Intercept Difference. These parameters will change when the f-number of the system changes due to the use of Barlow lenses or focal reducing lenses. We have provided a simple data base form, shown here, that records and preserves this data for each system configuration.
When a user selects a different system configuration, the System Profile for that unique system is selected. Every time that a V Curve is completed, the user has the option of saving the measured parameters in the System Profile database. Each row shown in the above form is the data from a single V Curve sequence. The values of the Left Slope, Right Slope and Position Intercept Difference found in the database are averaged and shown in the System Profile frame in the upper part of the form. The user can elect to include or exclude V Curve parameters from this average by placing a Y or N in the far left column of the database. In order to evaluate the quality of the V Curve data, the number of points used to measure the slopes for each V Curve side (NPTS) are tabulated as well as the standard deviation of the straight line fit to the V Curves for both the left and the right sides of the V Curve. When the user clicks the Update button, the averaged parameter values are used to update the actual parameters used to perform the Focus operation.
As mentioned above, we typically achieve a perfect focus one minute after the focus operation is initiated for a ST-8E CCD camera. This value is strongly dependent on how far the star is initially out of focus. Stars farther from focus obviously take longer due to focuser move time and may also require additional exposures.
Stars that are not too far from best focus can range between 7th and 1st magnitude for an 8 inch LX-200 and a ST-8E camera using 0.11-second exposures. We have made similar measurements on a custom built 10-inch Newtonian that utilizes a precision secondary mirror focuser. The high magnitude limit is determined by the low signal to noise ratio that gives lower accuracy HFD values. Of course dimmer target stars can be used with longer exposure times. The low magnitude limit is due to the saturation of the star on the CCD. This limit is strongly dependent on the user selected Near Focus Position. Absence of CCD saturation is most critical for the Near Focus exposures since they are used to determine the Best Focus Position. The user can reliably focus stars even brighter than 1st magnitude by adjusting the Near Focus Position so that the HFD values at the Near Focus Position are sufficiently large to avoid saturation.
The algorithm can accommodate out-of-focus star images that have diameters as large as 90% of the height of the CCD chip. The algorithm that determines the background level imposes this limit. If the background level was somehow known and properly subtracted, then the HFD algorithm could accommodate even larger star image diameters.
The software includes an ASCOM object  that can be called by user written scripts to control the focus operations along with other ASCOM controlled telescope operations [5,6]. The object contains the following Methods and Properties:
FindStar Finds the brightest star on chip, centers in small frame and calculates HFD
SingleExpose Takes single exposure in small frame and calculates HFD
HalfFluxDiameter (read only) The most recently measured Half Flux Diameter
Position (read only) The current RoboFocus Position
StarXCenter (read write) The CCD chip X coordinate of the star center
StarYCenter (read write) The CCD chip Y coordinate of the star center
SingleExposeFrameWidth (read write) Width in pixels of SingleExpose frame
The software described here is available in executable application form as freeware from the authors. It is currently at beta test status. It is written in Microsoft Visual Basic 6.0. To obtain the executable installation package contact:
Larry Weber firstname.lastname@example.org or
Steve Brady email@example.com .
Software downloads are available at http://www.focusmax.org .
 This paper is an updated version of our paper of the same title originally presented at the 2001 Minor Planet Amateur/Professional Workshop, pp.104-113, Tucson AZ.
 Technical Innovations RoboFocus stepper motor control. See http://www.homedome.com
 Diffraction Limited MaxIm DL CCD camera control. See http://www.cyanogen.com
 Astronomy Common Object Model (ASCOM). See http://www.ascom-standards.org
 Robert B. Denny, “ASCOM: Review of the Technology and Milestones,” 2001 Minor Planet Amateur/Professional Workshop, pp.88-92, Tucson AZ.
 Jeffrey S. Medkeff, “Small Robotic Observatories: Operations, Deployment and Future Direction,” 2001 Minor Planet Amateur/Professional Workshop, pp.93-103, Tucson AZ.