Exemple #1
0
def convertToMultiFit(i3data, x_size, y_size, frame, nm_per_pixel, inverted=False):
    """
    Create a 3D-DAOSTORM, sCMOS or Spliner analysis compatible peak array from I3 data.

    Notes:
      (1) This uses the non-drift corrected positions.
      (2) This sets the initial fitting error to zero and the status to RUNNING.
    """
    i3data = maskData(i3data, (i3data['fr'] == frame))

    peaks = numpy.zeros((i3data.size, utilC.getNPeakPar()))
    
    peaks[:,utilC.getBackgroundIndex()] = i3data['bg']
    peaks[:,utilC.getHeightIndex()] = i3data['h']
    peaks[:,utilC.getZCenterIndex()] = i3data['z'] * 0.001

    if inverted:
        peaks[:,utilC.getXCenterIndex()] = y_size - i3data['x']
        peaks[:,utilC.getYCenterIndex()] = x_size - i3data['y']
        ax = i3data['ax']
        ww = i3data['w']
        peaks[:,utilC.getYWidthIndex()] = 0.5*numpy.sqrt(ww*ww/ax)/nm_per_pixel
        peaks[:,utilC.getXWidthIndex()] = 0.5*numpy.sqrt(ww*ww*ax)/nm_per_pixel
    else:
        peaks[:,utilC.getYCenterIndex()] = i3data['x'] - 1
        peaks[:,utilC.getXCenterIndex()] = i3data['y'] - 1
        ax = i3data['ax']
        ww = i3data['w']
        peaks[:,utilC.getXWidthIndex()] = 0.5*numpy.sqrt(ww*ww/ax)/nm_per_pixel
        peaks[:,utilC.getYWidthIndex()] = 0.5*numpy.sqrt(ww*ww*ax)/nm_per_pixel

    return peaks
Exemple #2
0
    def __init__(self, parameters):

        # Initialized from parameters.
        self.find_max_radius = parameters.getAttr("find_max_radius", 5)     # Radius (in pixels) over which the maxima is maximal.
        self.iterations = parameters.getAttr("iterations")                  # Maximum number of cycles of peak finding, fitting and subtraction to perform.
        self.sigma = parameters.getAttr("sigma")                            # Peak sigma (in pixels).
        self.threshold = parameters.getAttr("threshold")                    # Peak minimum threshold (height, in camera units).
        self.z_value = parameters.getAttr("z_value", 0.0)                   # The starting z value to use for peak fitting.

        # Other member variables.
        self.background = None                                              # Current estimate of the image background.
        self.image = None                                                   # The original image.
        self.margin = PeakFinderFitter.margin                               # Size of the unanalyzed "edge" around the image.
        self.neighborhood = PeakFinder.unconverged_dist * self.sigma        # Radius for marking neighbors as unconverged.
        self.new_peak_radius = PeakFinder.new_peak_dist                     # Minimum allowed distance between new peaks and current peaks.
        self.parameters = parameters                                        # Keep access to the parameters object.
        self.peak_locations = None                                          # Initial peak locations, as explained below.
        self.peak_mask = None                                               # Mask for limiting peak identification to a particular AOI.
        self.taken = None                                                   # Spots in the image where a peak has already been added.

        
        #
        # This is for is you already know where your want fitting to happen, as
        # for example in a bead calibration movie and you just want to use the
        # approximate locations as inputs for fitting.
        #
        # peak_locations is a text file with the peak x, y, height and background
        # values as white spaced columns (x and y positions are in pixels as
        # determined using visualizer).
        #
        # 1.0 2.0 1000.0 100.0
        # 10.0 5.0 2000.0 200.0
        # ...
        #
        if parameters.hasAttr("peak_locations"):
            print("Using peak starting locations specified in", parameters.getAttr("peak_locations"))

            # Only do one cycle of peak finding as we'll always return the same locations.
            if (self.iterations != 1):
                print("WARNING: setting number of iterations to 1!")
                self.iterations = 1

            # Load peak x,y locations.
            peak_locs = numpy.loadtxt(parameters.getAttr("peak_locations"), ndmin = 2)
            print(peak_locs.shape)

            # Create peak array.
            self.peak_locations = numpy.zeros((peak_locs.shape[0],
                                               utilC.getNPeakPar()))
            self.peak_locations[:,utilC.getXCenterIndex()] = peak_locs[:,1] + self.margin
            self.peak_locations[:,utilC.getYCenterIndex()] = peak_locs[:,0] + self.margin
            self.peak_locations[:,utilC.getHeightIndex()] = peak_locs[:,2]
            self.peak_locations[:,utilC.getBackgroundIndex()] = peak_locs[:,3]

            self.peak_locations[:,utilC.getXWidthIndex()] = numpy.ones(peak_locs.shape[0]) * self.sigma
            self.peak_locations[:,utilC.getYWidthIndex()] = numpy.ones(peak_locs.shape[0]) * self.sigma
    def getPeaks(self, threshold, margin):
        """
        Extract peaks from the deconvolved image and create
        an array that can be used by a peak fitter.
        
        FIXME: Need to compensate for up-sampling parameter in x,y.
        """

        fx = self.getXVector()

        # Get area, position, height.
        fd_peaks = fdUtil.getPeaks(fx, threshold, margin)
        num_peaks = fd_peaks.shape[0]

        peaks = numpy.zeros((num_peaks, utilC.getNPeakPar()))

        peaks[:, utilC.getXWidthIndex()] = numpy.ones(num_peaks)
        peaks[:, utilC.getYWidthIndex()] = numpy.ones(num_peaks)

        peaks[:, utilC.getXCenterIndex()] = fd_peaks[:, 2]
        peaks[:, utilC.getYCenterIndex()] = fd_peaks[:, 1]

        # Calculate height.
        #
        # FIXME: Typically the starting value for the peak height will be
        #        under-estimated unless a large enough number of FISTA
        #        iterations is performed to completely de-convolve the image.
        #
        h_index = utilC.getHeightIndex()
        #peaks[:,h_index] = fd_peaks[:,0]
        for i in range(num_peaks):
            peaks[i, h_index] = fd_peaks[i, 0] * self.psf_heights[int(
                round(fd_peaks[i, 3]))]

        # Calculate z (0.0 - 1.0).
        if (fx.shape[2] > 1):
            peaks[:, utilC.getZCenterIndex()] = fd_peaks[:, 3] / (
                float(fx.shape[2]) - 1.0)

        # Background term calculation.
        bg_index = utilC.getBackgroundIndex()
        for i in range(num_peaks):
            ix = int(round(fd_peaks[i, 1]))
            iy = int(round(fd_peaks[i, 2]))
            peaks[i, bg_index] = self.background[ix, iy]

        return peaks
Exemple #4
0
def convertToMultiFit(i3data,
                      x_size,
                      y_size,
                      frame,
                      nm_per_pixel,
                      inverted=False):
    """
    Create a 3D-DAOSTORM, sCMOS or Spliner analysis compatible peak array from I3 data.

    Notes:
      (1) This uses the non-drift corrected positions.
      (2) This sets the initial fitting error to zero and the status to RUNNING.
    """
    i3data = maskData(i3data, (i3data['fr'] == frame))

    peaks = numpy.zeros((i3data.size, utilC.getNPeakPar()))

    peaks[:, utilC.getBackgroundIndex()] = i3data['bg']
    peaks[:, utilC.getHeightIndex()] = i3data['h']
    peaks[:, utilC.getZCenterIndex()] = i3data['z'] * 0.001

    if inverted:
        peaks[:, utilC.getXCenterIndex()] = y_size - i3data['x']
        peaks[:, utilC.getYCenterIndex()] = x_size - i3data['y']
        ax = i3data['ax']
        ww = i3data['w']
        peaks[:, utilC.getYWidthIndex()] = 0.5 * numpy.sqrt(
            ww * ww / ax) / nm_per_pixel
        peaks[:, utilC.getXWidthIndex()] = 0.5 * numpy.sqrt(
            ww * ww * ax) / nm_per_pixel
    else:
        peaks[:, utilC.getYCenterIndex()] = i3data['x'] - 1
        peaks[:, utilC.getXCenterIndex()] = i3data['y'] - 1
        ax = i3data['ax']
        ww = i3data['w']
        peaks[:, utilC.getXWidthIndex()] = 0.5 * numpy.sqrt(
            ww * ww / ax) / nm_per_pixel
        peaks[:, utilC.getYWidthIndex()] = 0.5 * numpy.sqrt(
            ww * ww * ax) / nm_per_pixel

    return peaks
def psfLocalizations(i3_filename, mapping_filename, frame = 1, aoi_size = 8, movie_filename = None):

    # Load localizations.
    i3_reader = readinsight3.I3Reader(i3_filename)

    # Load mapping.
    mappings = {}
    if os.path.exists(mapping_filename):
        with open(mapping_filename, 'rb') as fp:
            mappings = pickle.load(fp)
    else:
        print("Mapping file not found, single channel data?")

    # Try and determine movie frame size.
    i3_metadata = readinsight3.loadI3Metadata(i3_filename)
    if i3_metadata is None:
        if movie_filename is None:
            raise Exception("I3 metadata not found and movie filename is not specified.")
        else:
            movie_fp = datareader.inferReader(movie_filename)
            [movie_y, movie_x] = movie_fp.filmSize()[:2]
    else:
        movie_data = i3_metadata.find("movie")

        # FIXME: These may be transposed?
        movie_x = int(movie_data.find("movie_x").text)
        movie_y = int(movie_data.find("movie_y").text)
    
    # Load localizations in the requested frame.
    locs = i3_reader.getMoleculesInFrame(frame)
    print("Loaded", locs.size, "localizations.")

    # Remove localizations that are too close to each other.
    in_locs = numpy.zeros((locs["x"].size, util_c.getNPeakPar()))
    in_locs[:,util_c.getXCenterIndex()] = locs["x"]
    in_locs[:,util_c.getYCenterIndex()] = locs["y"]

    out_locs = util_c.removeNeighbors(in_locs, 2 * aoi_size)

    xf = out_locs[:,util_c.getXCenterIndex()]
    yf = out_locs[:,util_c.getYCenterIndex()]

    #
    # Remove localizations that are too close to the edge or
    # outside of the image in any of the channels.
    #
    is_good = numpy.ones(xf.size, dtype = numpy.bool)
    for i in range(xf.size):

        # Check in Channel 0.
        if (xf[i] < aoi_size) or (xf[i] + aoi_size >= movie_x):
            is_good[i] = False
            continue
        
        if (yf[i] < aoi_size) or (yf[i] + aoi_size >= movie_y):
            is_good[i] = False
            continue

        # Check other channels.
        for key in mappings:
            if not is_good[i]:
                break
            
            coeffs = mappings[key]
            [ch1, ch2, axis] = key.split("_")
            if (ch1 == "0"):

                if (axis == "x"):
                    xm = coeffs[0] + coeffs[1]*xf[i] + coeffs[2]*yf[i]
                    if (xm < aoi_size) or (xm + aoi_size >= movie_x):
                        is_good[i] = False
                        break

                elif (axis == "y"):
                    ym = coeffs[0] + coeffs[1]*xf[i] + coeffs[2]*yf[i]
                    if (ym < aoi_size) or (ym + aoi_size >= movie_y):
                        is_good[i] = False
                        break

    #
    # Save localizations for each channel.
    #
    gx = xf[is_good]
    gy = yf[is_good]

    basename = os.path.splitext(i3_filename)[0]
    with writeinsight3.I3Writer(basename + "_c1_psf.bin") as w3:
        w3.addMoleculesWithXY(gx, gy)
    
    index = 1
    while ("0_" + str(index) + "_x" in mappings):
        cx = mappings["0_" + str(index) + "_x"]
        cy = mappings["0_" + str(index) + "_y"]
        #cx = mappings[str(index) + "_0" + "_x"]
        #cy = mappings[str(index) + "_0" + "_y"]
        xm = cx[0] + cx[1] * gx + cx[2] * gy
        ym = cy[0] + cy[1] * gx + cy[2] * gy

        with writeinsight3.I3Writer(basename + "_c" + str(index+1) + "_psf.bin") as w3:
            w3.addMoleculesWithXY(xm, ym)

        index += 1

    #
    # Print localizations that were kept.
    #
    print(gx.size, "localizations were kept:")
    for i in range(gx.size):
        print("ch0: {0:.2f} {1:.2f}".format(gx[i], gy[i]))
        index = 1
        while ("0_" + str(index) + "_x" in mappings):
            cx = mappings["0_" + str(index) + "_x"]
            cy = mappings["0_" + str(index) + "_y"]
            xm = cx[0] + cx[1] * gx[i] + cx[2] * gy[i]
            ym = cy[0] + cy[1] * gx[i] + cy[2] * gy[i]
            print("ch" + str(index) + ": {0:.2f} {1:.2f}".format(xm, ym))
            index += 1
        print("")
    print("")
Exemple #6
0
    def __init__(self, parameters):
        """
        This is called once at the start of analysis to initialize the
        parameters that will be used for peak fitting.
 
        parameters - A parameters object.
        """
        # Initialized from parameters.
        self.find_max_radius = parameters.getAttr(
            "find_max_radius",
            5)  # Radius (in pixels) over which the maxima is maximal.
        self.iterations = parameters.getAttr(
            "iterations"
        )  # Maximum number of cycles of peak finding, fitting and subtraction to perform.
        self.sigma = parameters.getAttr("sigma")  # Peak sigma (in pixels).
        self.threshold = parameters.getAttr(
            "threshold")  # Peak minimum threshold (height, in camera units).
        self.z_value = parameters.getAttr(
            "z_value", 0.0)  # The starting z value to use for peak fitting.

        # Other member variables.
        self.background = None  # Current estimate of the image background.
        self.image = None  # The original image.
        self.margin = PeakFinderFitter.margin  # Size of the unanalyzed "edge" around the image.
        self.neighborhood = PeakFinder.unconverged_dist * self.sigma  # Radius for marking neighbors as unconverged.
        self.new_peak_radius = PeakFinder.new_peak_dist  # Minimum allowed distance between new peaks and current peaks.
        self.parameters = parameters  # Keep access to the parameters object.
        self.peak_locations = None  # Initial peak locations, as explained below.
        self.peak_mask = None  # Mask for limiting peak identification to a particular AOI.
        self.taken = None  # Spots in the image where a peak has already been added.

        #
        # This is for is you already know where your want fitting to happen, as
        # for example in a bead calibration movie and you just want to use the
        # approximate locations as inputs for fitting.
        #
        # peak_locations is a text file with the peak x, y, height and background
        # values as white spaced columns (x and y positions are in pixels as
        # determined using visualizer).
        #
        # 1.0 2.0 1000.0 100.0
        # 10.0 5.0 2000.0 200.0
        # ...
        #
        if parameters.hasAttr("peak_locations"):
            print("Using peak starting locations specified in",
                  parameters.getAttr("peak_locations"))

            # Only do one cycle of peak finding as we'll always return the same locations.
            if (self.iterations != 1):
                print("WARNING: setting number of iterations to 1!")
                self.iterations = 1

            # Load peak x,y locations.
            peak_locs = numpy.loadtxt(parameters.getAttr("peak_locations"),
                                      ndmin=2)
            print(peak_locs.shape)

            # Create peak array.
            self.peak_locations = numpy.zeros(
                (peak_locs.shape[0], utilC.getNPeakPar()))
            self.peak_locations[:, utilC.getXCenterIndex(
            )] = peak_locs[:, 1] + self.margin
            self.peak_locations[:, utilC.getYCenterIndex(
            )] = peak_locs[:, 0] + self.margin
            self.peak_locations[:, utilC.getHeightIndex()] = peak_locs[:, 2]
            self.peak_locations[:, utilC.getBackgroundIndex()] = peak_locs[:,
                                                                           3]

            self.peak_locations[:, utilC.getXWidthIndex()] = numpy.ones(
                peak_locs.shape[0]) * self.sigma
            self.peak_locations[:, utilC.getYWidthIndex()] = numpy.ones(
                peak_locs.shape[0]) * self.sigma
Exemple #7
0
                             ndpointer(dtype=numpy.float64),
                             ndpointer(dtype=numpy.float64),
                             c_double, 
                             c_int, 
                             c_int,
                             c_int,
                             c_int]
multi.initializeZParameters.argtypes = [ndpointer(dtype=numpy.float64), 
                                        ndpointer(dtype=numpy.float64),
                                        c_double,
                                        c_double]

# Globals
default_tol = 1.0e-6

peakpar_size = util_c.getNPeakPar()
resultspar_size = util_c.getNResultsPar()


##
# Helper functions.
##
def calcSxSy(wx_params, wy_params, z):
    zx = (z - wx_params[1])/wx_params[2]
    sx = 0.5 * wx_params[0] * math.sqrt(1.0 + zx*zx + wx_params[3]*zx*zx*zx + wx_params[4]*zx*zx*zx*zx)
    zy = (z - wy_params[1])/wy_params[2]
    sy = 0.5 * wy_params[0] * math.sqrt(1.0 + zy*zy + wy_params[3]*zy*zy*zy + wy_params[4]*zy*zy*zy*zy)
    return [sx, sy]

def fitStats(results):
    total = results.shape[0]
Exemple #8
0
def measurePSF(movie_name,
               zfile_name,
               movie_mlist,
               psf_name,
               want2d=False,
               aoi_size=12,
               z_range=750.0,
               z_step=50.0):
    """
    The actual z range is 2x z_range (i.e. from -z_range to z_range).
    """

    # Load dax file, z offset file and molecule list file.
    dax_data = datareader.inferReader(movie_name)
    z_offsets = None
    if os.path.exists(zfile_name):
        try:
            z_offsets = numpy.loadtxt(zfile_name, ndmin=2)[:, 1]
        except IndexError:
            z_offsets = None
            print("z offsets were not loaded.")
    i3_data = readinsight3.loadI3File(movie_mlist)

    if want2d:
        print("Measuring 2D PSF")
    else:
        print("Measuring 3D PSF")

    #
    # Go through the frames identifying good peaks and adding them
    # to the average psf. For 3D molecule z positions are rounded to
    # the nearest 50nm.
    #
    z_mid = int(z_range / z_step)
    max_z = 2 * z_mid + 1

    average_psf = numpy.zeros((max_z, 4 * aoi_size, 4 * aoi_size))
    peaks_used = 0
    totals = numpy.zeros(max_z)
    [dax_x, dax_y, dax_l] = dax_data.filmSize()
    for curf in range(dax_l):

        # Select localizations in current frame & not near the edges.
        mask = (i3_data['fr'] == curf + 1) & (i3_data['x'] > aoi_size) & (
            i3_data['x'] <
            (dax_x - aoi_size - 1)) & (i3_data['y'] >
                                       aoi_size) & (i3_data['y'] <
                                                    (dax_y - aoi_size - 1))
        xr = i3_data['x'][mask]
        yr = i3_data['y'][mask]

        # Use the z offset file if it was specified, otherwise use localization z positions.
        if z_offsets is None:
            if (curf == 0):
                print("Using fit z locations.")
            zr = i3_data['z'][mask]
        else:
            if (curf == 0):
                print("Using z offset file.")
            zr = numpy.ones(xr.size) * z_offsets[curf]

        ht = i3_data['h'][mask]

        # Remove localizations that are too close to each other.
        in_peaks = numpy.zeros((xr.size, util_c.getNPeakPar()))
        in_peaks[:, util_c.getXCenterIndex()] = xr
        in_peaks[:, util_c.getYCenterIndex()] = yr
        in_peaks[:, util_c.getZCenterIndex()] = zr
        in_peaks[:, util_c.getHeightIndex()] = ht

        out_peaks = util_c.removeNeighbors(in_peaks, 2 * aoi_size)
        #out_peaks = util_c.removeNeighbors(in_peaks, aoi_size)

        print(curf, "peaks in", in_peaks.shape[0], ", peaks out",
              out_peaks.shape[0])

        # Use remaining localizations to calculate spline.
        image = dax_data.loadAFrame(curf).astype(numpy.float64)

        xr = out_peaks[:, util_c.getXCenterIndex()]
        yr = out_peaks[:, util_c.getYCenterIndex()]
        zr = out_peaks[:, util_c.getZCenterIndex()]
        ht = out_peaks[:, util_c.getHeightIndex()]

        for i in range(xr.size):
            xf = xr[i]
            yf = yr[i]
            zf = zr[i]
            xi = int(xf)
            yi = int(yf)
            if want2d:
                zi = 0
            else:
                zi = int(round(zf / z_step) + z_mid)

            # check the z is in range
            if (zi > -1) and (zi < max_z):

                # get localization image
                mat = image[xi - aoi_size:xi + aoi_size,
                            yi - aoi_size:yi + aoi_size]

                # zoom in by 2x
                psf = scipy.ndimage.interpolation.zoom(mat, 2.0)

                # re-center image
                psf = scipy.ndimage.interpolation.shift(
                    psf, (-2.0 * (xf - xi), -2.0 * (yf - yi)), mode='nearest')

                # add to average psf accumulator
                average_psf[zi, :, :] += psf
                totals[zi] += 1

    # Force PSF to be zero (on average) at the boundaries.
    for i in range(max_z):
        edge = numpy.concatenate((average_psf[i, 0, :], average_psf[i, -1, :],
                                  average_psf[i, :, 0], average_psf[i, :, -1]))
        average_psf[i, :, :] -= numpy.mean(edge)

    # Normalize the PSF.
    if want2d:
        max_z = 1

    for i in range(max_z):
        print(i, totals[i])
        if (totals[i] > 0.0):
            average_psf[i, :, :] = average_psf[i, :, :] / numpy.sum(
                numpy.abs(average_psf[i, :, :]))

    average_psf = average_psf / numpy.max(average_psf)

    # Save PSF (in image form).
    if True:
        import storm_analysis.sa_library.daxwriter as daxwriter
        dxw = daxwriter.DaxWriter(
            os.path.join(os.path.dirname(psf_name), "psf.dax"),
            average_psf.shape[1], average_psf.shape[2])
        for i in range(max_z):
            dxw.addFrame(1000.0 * average_psf[i, :, :] + 100)
        dxw.close()

    # Save PSF.
    if want2d:
        psf_dict = {"psf": average_psf[0, :, :], "type": "2D"}

    else:
        cur_z = -z_range
        z_vals = []
        for i in range(max_z):
            z_vals.append(cur_z)
            cur_z += z_step

        psf_dict = {
            "psf": average_psf,
            "pixel_size": 0.080,  # 1/2 the camera pixel size in nm.
            "type": "3D",
            "zmin": -z_range,
            "zmax": z_range,
            "zvals": z_vals
        }

    with open(psf_name, 'wb') as fp:
        pickle.dump(psf_dict, fp)
Exemple #9
0
def measurePSF(movie_name, zfile_name, movie_mlist, psf_name, want2d = False, aoi_size = 12, z_range = 750.0, z_step = 50.0):
    """
    The actual z range is 2x z_range (i.e. from -z_range to z_range).
    """
    
    # Load dax file, z offset file and molecule list file.
    dax_data = datareader.inferReader(movie_name)
    z_offsets = None
    if os.path.exists(zfile_name):
        try:
            z_offsets = numpy.loadtxt(zfile_name, ndmin = 2)[:,1]
        except IndexError:
            z_offsets = None
            print("z offsets were not loaded.")
    i3_data = readinsight3.loadI3File(movie_mlist)

    if want2d:
        print("Measuring 2D PSF")
    else:
        print("Measuring 3D PSF")

    #
    # Go through the frames identifying good peaks and adding them
    # to the average psf. For 3D molecule z positions are rounded to 
    # the nearest 50nm.
    #
    z_mid = int(z_range/z_step)
    max_z = 2 * z_mid + 1

    average_psf = numpy.zeros((max_z,4*aoi_size,4*aoi_size))
    peaks_used = 0
    totals = numpy.zeros(max_z)
    [dax_x, dax_y, dax_l] = dax_data.filmSize()
    for curf in range(dax_l):

        # Select localizations in current frame & not near the edges.
        mask = (i3_data['fr'] == curf+1) & (i3_data['x'] > aoi_size) & (i3_data['x'] < (dax_x - aoi_size - 1)) & (i3_data['y'] > aoi_size) & (i3_data['y'] < (dax_y - aoi_size - 1))
        xr = i3_data['x'][mask]
        yr = i3_data['y'][mask]

        # Use the z offset file if it was specified, otherwise use localization z positions.
        if z_offsets is None:
            if (curf == 0):
                print("Using fit z locations.")
            zr = i3_data['z'][mask]
        else:
            if (curf == 0):
                print("Using z offset file.")
            zr = numpy.ones(xr.size) * z_offsets[curf]

        ht = i3_data['h'][mask]

        # Remove localizations that are too close to each other.
        in_peaks = numpy.zeros((xr.size,util_c.getNPeakPar()))
        in_peaks[:,util_c.getXCenterIndex()] = xr
        in_peaks[:,util_c.getYCenterIndex()] = yr
        in_peaks[:,util_c.getZCenterIndex()] = zr
        in_peaks[:,util_c.getHeightIndex()] = ht

        out_peaks = util_c.removeNeighbors(in_peaks, 2*aoi_size)
        #out_peaks = util_c.removeNeighbors(in_peaks, aoi_size)

        print(curf, "peaks in", in_peaks.shape[0], ", peaks out", out_peaks.shape[0])

        # Use remaining localizations to calculate spline.
        image = dax_data.loadAFrame(curf).astype(numpy.float64)

        xr = out_peaks[:,util_c.getXCenterIndex()]
        yr = out_peaks[:,util_c.getYCenterIndex()]
        zr = out_peaks[:,util_c.getZCenterIndex()]
        ht = out_peaks[:,util_c.getHeightIndex()]

        for i in range(xr.size):
            xf = xr[i]
            yf = yr[i]
            zf = zr[i]
            xi = int(xf)
            yi = int(yf)
            if want2d:
                zi = 0
            else:
                zi = int(round(zf/z_step) + z_mid)

            # check the z is in range
            if (zi > -1) and (zi < max_z):

                # get localization image
                mat = image[xi-aoi_size:xi+aoi_size,
                            yi-aoi_size:yi+aoi_size]

                # zoom in by 2x
                psf = scipy.ndimage.interpolation.zoom(mat, 2.0)

                # re-center image
                psf = scipy.ndimage.interpolation.shift(psf, (-2.0*(xf-xi), -2.0*(yf-yi)), mode='nearest')

                # add to average psf accumulator
                average_psf[zi,:,:] += psf
                totals[zi] += 1

    # Force PSF to be zero (on average) at the boundaries.
    for i in range(max_z):
        edge = numpy.concatenate((average_psf[i,0,:],
                                  average_psf[i,-1,:],
                                  average_psf[i,:,0],
                                  average_psf[i,:,-1]))
        average_psf[i,:,:] -= numpy.mean(edge)

    # Normalize the PSF.
    if want2d:
        max_z = 1

    for i in range(max_z):
        print(i, totals[i])
        if (totals[i] > 0.0):
            average_psf[i,:,:] = average_psf[i,:,:]/numpy.sum(numpy.abs(average_psf[i,:,:]))

    average_psf = average_psf/numpy.max(average_psf)

    # Save PSF (in image form).
    if True:
        import storm_analysis.sa_library.daxwriter as daxwriter
        dxw = daxwriter.DaxWriter(os.path.join(os.path.dirname(psf_name), "psf.dax"),
                                  average_psf.shape[1],
                                  average_psf.shape[2])
        for i in range(max_z):
            dxw.addFrame(1000.0 * average_psf[i,:,:] + 100)
        dxw.close()

    # Save PSF.
    if want2d:
        psf_dict = {"psf" : average_psf[0,:,:],
                    "type" : "2D"}

    else:
        cur_z = -z_range
        z_vals = []
        for i in range(max_z):
            z_vals.append(cur_z)
            cur_z += z_step

        psf_dict = {"psf" : average_psf,
                    "pixel_size" : 0.080, # 1/2 the camera pixel size in nm.
                    "type" : "3D",
                    "zmin" : -z_range,
                    "zmax" : z_range,
                    "zvals" : z_vals}

    pickle.dump(psf_dict, open(psf_name, 'wb'))