Example #1
0
def debug(log, msg, level=logging.DEBUG):
    """
    do logging
    """
    levelName = _getLevelName(level)
    exec('log.%s(msg)' % levelName)
    level = _getLevel(level)
    if log.getEffectiveLevel() <= level:
        try:
            Y.refresh()
        except:
            pass
    else:
        pass
Example #2
0
def debug(log, msg, level=logging.DEBUG):
    """
    do logging
    """
    levelName = _getLevelName(level)
    exec('log.%s(msg)' % levelName)
    level = _getLevel(level)
    if log.getEffectiveLevel() <= level:
        try:
            Y.refresh()
        except:
            pass
    else:
        pass
Example #3
0
def main(*args):
    """
    aks for filenames
    tells you finished files using shell Messages
    """
    import wx
    from Priithon.all import Y

    dlg = wx.FileDialog(None,
                        'Choose image files',
                        style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)
    if dlg.ShowModal() == wx.ID_OK:
        fns = dlg.GetPaths()
        if fns:
            if isinstance(fns, basestring):
                fns = [fns]
            for fn in fns:
                #out = os.path.extsep.join((fn, DEF_EXT))
                out = byteSwap(fn)  #, out, DEF_BYTE)
                if hasattr(Y, 'shellMessage'):
                    Y.shellMessage(out.join(('#', '---done\n')))
                else:
                    print out.join(('#', '---done\n'))
                Y.refresh()
Example #4
0
def beads_analyzeBeads(fn,
                       thre_sigma=1.,
                       refwave=2,
                       nbeads=60,
                       win=5,
                       maxdist=600,
                       maxrefdist=5):  #0.6, maxrefdist=0.005):
    """
    maxdist: nm
    maxrefdist: nm

    return dic
    """
    from PriCommon import mrcIO, imgFilters, imgFit, imgGeo, microscope
    from Priithon.all import Y
    h = mrcIO.MrcReader(fn)
    if refwave >= h.nw:
        raise ValueError, 'reference wave does not exists'
    shape = h.hdr.Num[::-1].copy()
    shape[0] /= (h.hdr.NumTimes * h.hdr.NumWaves)
    pzyx = h.hdr.d[::-1]

    NA = 1.35
    difflimitYX = microscope.resolution(NA, h.hdr.wave[refwave]) / 1000.
    difflimit = N.array([difflimitYX * 2, difflimitYX, difflimitYX]) / pzyx
    print 'diffraction limit (px) is:', difflimit
    simres = difflimit / 1.5  #2.

    arr = h.get3DArr(w=refwave).copy()
    ndim = arr.ndim
    me = arr.mean()
    sd = arr.std()
    thre = me + sd * thre_sigma
    sigma = 1.5

    zyxs = []
    #found = []
    sigmas = []
    i = 0
    pmax = 0
    failed = 0
    while i < nbeads:
        Y.refresh()
        amax, z, y, x = U.findMax(arr)
        zyx = N.array((z, y, x), N.float32)
        #found.append(zyx)
        zyx0 = N.where(zyx > simres, zyx - simres, 0).astype(N.int)
        zyx1 = N.where(zyx + simres < shape, zyx + simres, shape).astype(N.int)
        rmslice = [slice(*zyx) for zyx in zip(zyx0, zyx1)]

        if failed > 10:
            raise RuntimeError
            break
        elif amax == pmax:
            arr[rmslice] = me
        elif amax > thre:
            # Gaussian fitting
            try:
                ret, check = imgFit.fitGaussianND(arr, [z, y, x][-ndim:],
                                                  sigma, win)
            except IndexError:  # too close to the edge
                arr[rmslice] = me
                print 'Index Error, too close to the edge', z, y, x
                failed += 1
                continue
            if check == 5:
                arr[rmslice] = me
                print 'fit failed', z, y, x
                failed += 1
                continue

            # retreive results
            v = ret[1]
            zyx = ret[2:2 + ndim]
            sigma = ret[2 + ndim:2 + ndim * 2]
            if any(sigma) < 1:
                sigma = N.where(sigma < 1, 1, sigma)

            # check if the result is inside the image
            if N.any(zyx < 0) or N.any(zyx > (shape)):
                print 'fitting results outside the image', zyx, z, y, x, rmslice
                arr[rmslice] = me
                failed += 1
                continue  # too close to the edge

            # remove the point
            imgFilters.mask_gaussianND(arr, zyx, v, sigma)

            # check if the bead is too close to the exisisting ones
            skipped = """
            if len(found):#zyxs):
                close = imgGeo.closeEnough(zyx, found, difflimit*2)#zyxs, difflimit*2)
                if N.any(close):
                    if len(zyxs):
                        close = imgGeo.closeEnough(zyx, zyxs, difflimit*2)
                        if N.any(close):
                            idx = close.argmax()
                            already = zyxs.pop(idx)
                            #print 'too close', zyx, already
                    print 'found in the previous list'
                    continue"""

            # remove beads too close to the edge
            if N.any(zyx < 2) or N.any(zyx > (shape - 2)):
                print 'too close to the edge', zyx
                if N.any(arr[rmslice] > thre):
                    arr[rmslice] = me
                failed += 1
                continue  # too close to the edge

            # remove beads with bad shape
            elif N.any(sigma < 0.5) or N.any(sigma > 3):
                print 'sigma too different from expected', sigma, zyx
                if N.any(arr[rmslice] > thre):
                    arr[rmslice] = me
                sigma = 1.5
                failed += 1
                continue

            old = """
            # remove beads too elliptic
            elif sigma[1] / sigma[2] > 1.5 or sigma[2] / sigma[1] > 1.5:
                print 'too elliptic', sigma[2] / sigma[1]
                if N.any(arr[rmslice] > thre):
                    arr[rmslice] = me
                    #if (sigma[2] / sigma[1]) > 20:
                    #raise ValueError
                sigma = 1.5
                failed += 1
                continue

            elif N.any(sigma[-2:] > 3.0):
                print 'sigma too large', sigma, zyx
                if N.any(arr[rmslice] > thre):
                    arr[rmslice] = me
                sigma = 1.5
                failed += 1
                continue

            elif sigma[0] < 0.5 or sigma[0] > 3:
                print 'sigma z too different from expected', sigma, zyx
                if N.any(arr[rmslice] > thre):
                    arr[rmslice] = me
                sigma = 1.5
                failed += 1
                continue


            #elif imgGeo.closeEnough(zyx, N.array((17,719,810), N.float32), 4):
            #    raise RuntimeError"""

            # add results
            zyxs.append(zyx)
            sigmas.append(sigma)
            i += 1
            pmax = amax
            failed = 0
            #print i

        # maximum is below threshold
        else:
            break
    del arr

    sigmas = N.array(sigmas)
    sigmaYX = N.mean(sigmas[:, 1:], axis=1)
    sigmaZ = sigmas[:, 0]
    idxyx = sigmaYX.argmax()
    idxz = sigmaZ.argmax()
    print 'sigmaYX', round(sigmaYX.mean(),
                           3), round(sigmaYX.min(),
                                     3), round(sigmaYX.std(),
                                               3), round(sigmaYX.max(),
                                                         3), zyxs[idxyx]
    print 'sigmaZ', round(sigmaZ.mean(),
                          3), round(sigmaZ.min(),
                                    3), round(sigmaZ.std(),
                                              3), round(sigmaZ.max(),
                                                        3), zyxs[idxz]

    # remove overlaps
    zyxs2 = []
    zyxs = N.array(zyxs)
    for i, zyx in enumerate(zyxs):
        close = imgGeo.closeEnough(zyx, zyxs, difflimit * 4)
        if not N.any(close[:i]) and not N.any(close[i + 1:]):
            #idx = close.argmax()
            #already = zyxs.pop(idx)
            zyxs2.append(zyx)
    zyxs = zyxs2

    waves = range(h.nw)
    #waves.remove(refwave)

    difdic = {}
    removes = []

    checks = 0
    zeros = 0
    toofars = 0

    pzyx *= 1000

    for w in waves:
        if w == refwave:
            continue
        arr = h.get3DArr(w=w)
        #me = arr.mean()
        #sd = arr.std()
        #thre = me + sd * thre_sigma

        for zyx in zyxs:
            key = tuple(zyx * pzyx)
            if key in removes:
                continue

            #win0 = win
            #while win0 >= 3:
            try:
                ret, check = imgFit.fitGaussianND(arr,
                                                  zyx,
                                                  sigma=sigma,
                                                  window=win)  #0)
                #break
            except (IndexError, ValueError):
                ret = zyx
                check = 5
                #win0 -= 2
                #ret, check = imgFit.fitGaussianND(arr, zyx, sigma=sigma, window=3)

            dif = (zyx - ret[2:5]) * pzyx
            if check == 5 or (
                    w != refwave and N.any(N.abs(dif) > maxdist)) or (
                        w == refwave and N.any(N.abs(dif) > maxrefdist)
                    ):  #(N.all(dif == 0) or N.any(N.abs(dif) > maxdist))):
                if check == 5:
                    checks += 1
                    #elif N.all(dif == 0):
                    #zeros += 1
                elif w == refwave and N.any(N.abs(dif) > maxrefdist):
                    zeros += 1
                elif N.any(N.abs(dif) > maxdist):
                    toofars += 1
                #if N.any(N.abs(dif) > maxdist):
                #    raise ValueError
                #raise RuntimeError
                removes.append(key)
                if difdic.has_key(key):
                    del difdic[key]
                #elif not N.sum(dif) or N.any(dif > 10):
                #raise RuntimeError, 'something is wrong'
            else:
                difdic.setdefault(key, [])
                difdic[key].append(dif)
                sigma = ret[5:8]
                #del arr

    h.close()
    del arr
    del h

    print 'check:', checks, 'zeros:', zeros, 'toofars', toofars

    # subtracting the center
    newdic = {}
    keys = difdic.keys()
    newkeys = N.array(keys)
    zmin = N.min(newkeys[:, 0])
    center = (shape * pzyx) / 2.
    #yx0 = (N.max(newkeys[:,1:], axis=0) - N.min(newkeys[:,1:], axis=0)) / 2.
    newkeys[:, 0] -= zmin
    newkeys[:, 1:] -= center[1:]  #yx0
    newkeys = [tuple(key) for key in newkeys]

    items = [difdic[key] for key in keys]
    newdic = dict(zip(newkeys, items))
    difdic = newdic

    # plot
    P.figure(0, figsize=(8, 8))
    keys = N.array(difdic.keys())
    P.hold(0)
    P.scatter(keys[:, 2], keys[:, 1], alpha=0.5)
    P.xlabel('X (nm)')
    P.ylabel('Y (nm)')
    P.savefig(fn + '_fig0.png')

    return difdic  #, shape