Esempio n. 1
0
from peri import util
import numpy as np
from peri.comp import objs
from peri.viz.interaction import OrthoPrefeature
from peri import models
from peri import states
from peri import comp
from peri import runner
from peri.viz import plots
from datetime import datetime


imFile = '/Volumes/PhD/expDesign/test/balls.tif'
blank_im = util.RawImage(imFile)
particle_positions=np.load('part_loc_davidImage.npy')
# particle_positions
n=100
# random_particles = np.c_[np.random.random(n), np.random.random(n),np.zeros(n)]*200.0
tile = util.Tile(200)
small_im = util.RawImage(imFile, tile=tile)

zpixel=1
xpixel=1
zscale=zpixel/xpixel

particle_radii = 8.0
particles = objs.PlatonicSpheresCollection(particle_positions, particle_radii, zscale=zscale)

objects = comp.comp.ComponentCollection([particles], category='obj')

Esempio n. 2
0
def translate_featuring(state_name=None,
                        im_name=None,
                        use_full_path=False,
                        **kwargs):
    """
    Translates one optimized state into another image where the particles
    have moved by a small amount (~1 particle radius).

    Returns a completely-optimized state. The user can interactively
    selects the initial state and the second raw image. The state is
    periodically saved during optimization, with different filename for
    different stages of the optimization.

    Parameters
    ----------
        state_name : String or None, optional
            The name of the initially-optimized state. Default is None,
            which prompts the user to select the name interactively
            through a Tk window.
        im_name : String or None, optional
            The name of the new image to optimize. Default is None,
            which prompts the user to select the name interactively
            through a Tk window.
        use_full_path : Bool, optional
            Set to True to use the full path of the state instead of
            partial path names (e.g. /full/path/name/state.pkl vs
            state.pkl). Default is False

    Other Parameters
    ----------------
        max_mem : Numeric
            The maximum additional memory to use for the optimizers, as
            passed to optimize.burn. Default is 1e9.
        desc : String, optional
            A description to be inserted in saved state. The save name will
            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''
        min_rad : Float, optional
            The minimum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius smaller than this are identified
            as fake and removed. Default is 0.5 * actual_rad.
        max_rad : Float, optional
            The maximum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius larger than this are identified
            as fake and removed. Default is 1.5 * actual_rad, however you
            may find better results if you make this more stringent.
        invert : {True, False, 'guess'}
            Whether to invert the image for featuring, as passed to
            addsubtract.add_subtract. Default is to guess from the
            state's current particles.
        rz_order : int, optional
            If nonzero, the order of an additional augmented rscl(z)
            parameter for optimization. Default is 0; i.e. no rscl(z)
            optimization.
        do_polish : Bool, optional
            Set to False to only optimize the particles and add-subtract.
            Default is True, which then runs a polish afterwards.

    Returns
    -------
        s : :class:`peri.states.ImageState`
            The optimized state.

    See Also
    --------
        get_initial_featuring   : Features an image from scratch, using
            centroid methods as initial particle locations.

        feature_from_pos_rad    : Using a previous state's globals and
            user-provided positions and radii as an initial guess,
            completely optimizes a state.

        get_particle_featuring  : Using a previous state's globals and
            positions as an initial guess, completely optimizes a state.

    Notes
    -----
    The ``Other Parameters`` are passed to _translate_particles.
    Proceeds by:
        1. Optimize particle positions only.
        2. Optimize particle positions and radii only.
        3. Add-subtract missing and bad particles.
        4. If polish, optimize the illumination, background, and particles.
        5. If polish, optimize everything.
    """
    state_name, im_name = _pick_state_im_name(state_name,
                                              im_name,
                                              use_full_path=use_full_path)

    s = states.load(state_name)
    im = util.RawImage(im_name, tile=s.image.tile)

    s.set_image(im)
    _translate_particles(s, **kwargs)
    return s
Esempio n. 3
0
def get_particles_featuring(feature_rad,
                            state_name=None,
                            im_name=None,
                            use_full_path=False,
                            actual_rad=None,
                            invert=True,
                            featuring_params={},
                            **kwargs):
    """
    Combines centroid featuring with the globals from a previous state.

    Runs trackpy.locate on an image, sets the globals from a previous state,
    calls _translate_particles

    Parameters
    ----------
        feature_rad : Int, odd
            The particle radius for featuring, as passed to locate_spheres.

        state_name : String or None, optional
            The name of the initially-optimized state. Default is None,
            which prompts the user to select the name interactively
            through a Tk window.
        im_name : String or None, optional
            The name of the new image to optimize. Default is None,
            which prompts the user to select the name interactively
            through a Tk window.
        use_full_path : Bool, optional
            Set to True to use the full path of the state instead of
            partial path names (e.g. /full/path/name/state.pkl vs
            state.pkl). Default is False
        actual_rad : Float or None, optional
            The initial guess for the particle radii. Default is the median
            of the previous state.
        invert : Bool
            Whether to invert the image for featuring, as passed to
            addsubtract.add_subtract and locate_spheres. Set to False
            if the image is bright particles on a dark background.
            Default is True (dark particles on bright background).
        featuring_params : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.
            Default is ``{}``.


    Other Parameters
    ----------------
        max_mem : Numeric
            The maximum additional memory to use for the optimizers, as
            passed to optimize.burn. Default is 1e9.
        desc : String, optional
            A description to be inserted in saved state. The save name will
            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''
        min_rad : Float, optional
            The minimum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius smaller than this are identified
            as fake and removed. Default is 0.5 * actual_rad.
        max_rad : Float, optional
            The maximum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius larger than this are identified
            as fake and removed. Default is 1.5 * actual_rad, however you
            may find better results if you make this more stringent.
        rz_order : int, optional
            If nonzero, the order of an additional augmented rscl(z)
            parameter for optimization. Default is 0; i.e. no rscl(z)
            optimization.
        do_polish : Bool, optional
            Set to False to only optimize the particles and add-subtract.
            Default is True, which then runs a polish afterwards.

    Returns
    -------
        s : :class:`peri.states.ImageState`
            The optimized state.

    See Also
    --------
        get_initial_featuring   : Features an image from scratch, using
            centroid methods as initial particle locations.

        feature_from_pos_rad    : Using a previous state's globals and
            user-provided positions and radii as an initial guess,
            completely optimizes a state.

        translate_featuring     : Use a previous state's globals and
            centroids methods for an initial particle guess, completely
            optimizes a state.

    Notes
    -----
        The ``Other Parameters`` are passed to _translate_particles.
    Proceeds by:
        1. Find a guess of the particle positions through centroid methods.
        2. Optimize particle positions only.
        3. Optimize particle positions and radii only.
        4. Add-subtract missing and bad particles.
        5. If polish, optimize the illumination, background, and particles.
        6. If polish, optimize everything.
    """
    state_name, im_name = _pick_state_im_name(state_name,
                                              im_name,
                                              use_full_path=use_full_path)
    s = states.load(state_name)

    if actual_rad is None:
        actual_rad = np.median(s.obj_get_radii())
    im = util.RawImage(im_name, tile=s.image.tile)
    pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)
    _ = s.obj_remove_particle(np.arange(s.obj_get_radii().size))
    s.obj_add_particle(pos, np.ones(pos.shape[0]) * actual_rad)

    s.set_image(im)
    _translate_particles(s, invert=invert, **kwargs)
    return s
Esempio n. 4
0
def feature_from_pos_rad(statemaker,
                         pos,
                         rad,
                         im_name=None,
                         tile=None,
                         desc='',
                         use_full_path=False,
                         statemaker_kwargs={},
                         **kwargs):
    """
    Gets a completely-optimized state from an image and an initial guess of
    particle positions and radii.

    The state is periodically saved during optimization, with different
    filename for different stages of the optimization. The user can select
    the image.

    Parameters
    ----------
        statemaker : Function
            A statemaker function. Given arguments `im` (a
            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),
            and any additional `statemaker_kwargs`, must return a
            :class:`~peri.states.ImageState`.  There is an example function in
            scripts/statemaker_example.py
        pos : [N,3] element numpy.ndarray.
            The initial guess for the N particle positions.
        rad : N element numpy.ndarray.
            The initial guess for the N particle radii.
        im_name : string or None, optional
            The filename of the image to feature. Default is None, in which
            the user selects the image.
        tile : :class:`peri.util.Tile`, optional
            A tile of the sub-region of the image to feature. Default is
            None, i.e. entire image.
        desc : String, optional
            A description to be inserted in saved state. The save name will
            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''
        use_full_path : Bool, optional
            Set to True to use the full path name for the image. Default
            is False.
        statemaker_kwargs : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            the statemaker function. Default is ``{}``.

    Other Parameters
    ----------------
        max_mem : Numeric
            The maximum additional memory to use for the optimizers, as
            passed to optimize.burn. Default is 1e9.
        min_rad : Float, optional
            The minimum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius smaller than this are identified
            as fake and removed. Default is 0.5 * actual_rad.
        max_rad : Float, optional
            The maximum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius larger than this are identified
            as fake and removed. Default is 1.5 * actual_rad, however you
            may find better results if you make this more stringent.
        invert : {'guess', True, False}
            Whether to invert the image for featuring, as passed to
            addsubtract.add_subtract. Default is to guess from the
            current state's particle positions.
        rz_order : int, optional
            If nonzero, the order of an additional augmented rscl(z)
            parameter for optimization. Default is 0; i.e. no rscl(z)
            optimization.
        zscale : Float, optional
            The zscale of the image. Default is 1.0

    Returns
    -------
        s : :class:`peri.states.ImageState`
            The optimized state.

    See Also
    --------
        get_initial_featuring   : Features an image from scratch, using
            centroid methods as initial particle locations.

        get_particle_featuring  : Using a previous state's globals and
            positions as an initial guess, completely optimizes a state.

        translate_featuring     : Use a previous state's globals and
            centroids methods for an initial particle guess, completely
            optimizes a state.

    Notes
    -----
    The ``Other Parameters`` are passed to _optimize_from_centroid.
    Proceeds by centroid-featuring the image for an initial guess of
    particle positions, then optimizing the globals + positions until
    termination as called in _optimize_from_centroid.
    """
    if np.size(pos) == 0:
        raise ValueError('`pos` is an empty array.')
    elif np.shape(pos)[1] != 3:
        raise ValueError('`pos` must be an [N,3] element numpy.ndarray.')
    _, im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)
    im = util.RawImage(im_name, tile=tile)
    s = statemaker(im, pos, rad, **statemaker_kwargs)
    RLOG.info('State Created.')
    if desc is not None:
        states.save(s, desc=desc + 'initial')
    optimize_from_initial(s, desc=desc, **kwargs)
    return s
Esempio n. 5
0
def get_initial_featuring(statemaker,
                          feature_rad,
                          actual_rad=None,
                          im_name=None,
                          tile=None,
                          invert=True,
                          desc='',
                          use_full_path=False,
                          featuring_params={},
                          statemaker_kwargs={},
                          **kwargs):
    """
    Completely optimizes a state from an image of roughly monodisperse
    particles.

    The user can interactively select the image. The state is periodically
    saved during optimization, with different filename for different stages
    of the optimization.

    Parameters
    ----------
        statemaker : Function
            A statemaker function. Given arguments `im` (a
            :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),
            and any additional `statemaker_kwargs`, must return a
            :class:`~peri.states.ImageState`.  There is an example function in
            scripts/statemaker_example.py
        feature_rad : Int, odd
            The particle radius for featuring, as passed to locate_spheres.
        actual_rad : Float, optional
            The actual radius of the particles. Default is feature_rad
        im_name : string, optional
            The file name of the image to load. If not set, it is selected
            interactively through Tk.
        tile : :class:`peri.util.Tile`, optional
            The tile of the raw image to be analyzed. Default is None, the
            entire image.
        invert : Bool, optional
            Whether to invert the image for featuring, as passed to trackpy.
            Default is True.
        desc : String, optional
            A description to be inserted in saved state. The save name will
            be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''
        use_full_path : Bool, optional
            Set to True to use the full path name for the image. Default
            is False.
        featuring_params : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.
            Default is ``{}``.
        statemaker_kwargs : Dict, optional
            kwargs-like dict of any additional keyword arguments to pass to
            the statemaker function. Default is ``{}``.

    Other Parameters
    ----------------
        max_mem : Numeric
            The maximum additional memory to use for the optimizers, as
            passed to optimize.burn. Default is 1e9.
        min_rad : Float, optional
            The minimum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius smaller than this are identified
            as fake and removed. Default is 0.5 * actual_rad.
        max_rad : Float, optional
            The maximum particle radius, as passed to addsubtract.add_subtract.
            Particles with a fitted radius larger than this are identified
            as fake and removed. Default is 1.5 * actual_rad, however you
            may find better results if you make this more stringent.
        rz_order : int, optional
            If nonzero, the order of an additional augmented rscl(z)
            parameter for optimization. Default is 0; i.e. no rscl(z)
            optimization.
        zscale : Float, optional
            The zscale of the image. Default is 1.0

    Returns
    -------
        s : :class:`peri.states.ImageState`
            The optimized state.

    See Also
    --------
        feature_from_pos_rad    : Using a previous state's globals and
            user-provided positions and radii as an initial guess,
            completely optimizes a state.

        get_particle_featuring  : Using a previous state's globals and
            positions as an initial guess, completely optimizes a state.

        translate_featuring     : Use a previous state's globals and
            centroids methods for an initial particle guess, completely
            optimizes a state.

    Notes
    -----
    Proceeds by centroid-featuring the image for an initial guess of
    particle positions, then optimizing the globals + positions until
    termination as called in _optimize_from_centroid.
    The ``Other Parameters`` are passed to _optimize_from_centroid.
    """
    if actual_rad is None:
        actual_rad = feature_rad

    _, im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)
    im = util.RawImage(im_name, tile=tile)

    pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)
    if np.size(pos) == 0:
        msg = 'No particles found. Try using a smaller `feature_rad`.'
        raise ValueError(msg)

    rad = np.ones(pos.shape[0], dtype='float') * actual_rad
    s = statemaker(im, pos, rad, **statemaker_kwargs)
    RLOG.info('State Created.')
    if desc is not None:
        states.save(s, desc=desc + 'initial')
    optimize_from_initial(s, invert=invert, desc=desc, **kwargs)
    return s
Esempio n. 6
0
import matplotlib
# matplotlib.rcParams["backend"]="TkAgg"
from peri import util
import numpy as np
from peri.comp import objs
from peri.viz.interaction import OrthoPrefeature
from peri import models
from peri import states
from peri import comp
from peri import runner
from peri.viz import plots

from datetime import datetime

im = util.RawImage(
    '/Volumes/PhD/expDesign/Data/2011_DAS_SoftMatter_Data/jtLLF090701_BR090729_NBD_xyz007_x100_z35_K4.tif'
)

tile = util.Tile([5, 312, 0], right=[12, 512, 200])
small_im = util.RawImage(
    '/Volumes/PhD/expDesign/Data/2011_DAS_SoftMatter_Data/jtLLF090701_BR090729_NBD_xyz007_x100_z35_K4.tif',
    tile=tile)
zpixel = 0.82
xpixel = 35.2 / 512
zscale = zpixel / xpixel

particle_positions = np.load('part_loc_smallSlice.npy')
particle_radii = 8.0
particles = objs.PlatonicSpheresCollection(particle_positions,
                                           particle_radii,
                                           zscale=zscale)
Esempio n. 7
0
# ``image`` taken without a sample -- and gradually move up in complexity
# to a real microscope image.
import numpy as np
import matplotlib.pyplot as plt

from peri import states
from peri import models
from peri import util
from peri.comp import ilms, objs, exactpsf, comp
import peri.opt.optimize as opt

from peri.viz.interaction import *  # OrthoViewer & OrthoManipulator

# We start with featuring just a background image
# This image was taken with no sample, i.e. we're just measuring dark current
im_bkg = util.RawImage('./bkg_test.tif')  # located in the scripts folder

# First we try with just a constant background
bkg_const = ilms.LegendrePoly3D(order=(1, 1, 1))
# Since we're just fitting a blank image, we don't need a psf at first, so we
# use the simplest model for the state: a SmoothFieldModel, which has just
# returns the illumination field:
st = states.ImageState(im_bkg, [bkg_const], mdl=models.SmoothFieldModel())
opt.do_levmarq(st, st.params)


# Since there's not a whole lot to see in this image, looking at the
# OrthoViewer or OrthoManipulator doesn't provide a lot of insight. Instead,
# we look at plots of the residuals along certain axes. We'll do this several
# times so I'll make a function:
def plot_averaged_residuals(st):
Esempio n. 8
0
from peri import util
from peri.viz.interaction import OrthoViewer
import matplotlib

im = util.RawImage('../../Downloads/small_confocal_image.tif')

import numpy
from peri.comp import objs

coverslip = objs.Slab(zpos=6)
particle_positions = numpy.load('../../Downloads/particle-positions.npy')
particle_radii = 5.0
particles = objs.PlatonicSpheresCollection(particle_positions, particle_radii)

from peri.comp import comp

objects = comp.ComponentCollection([particles, coverslip], category='obj')

from peri.comp import ilms

illumination = ilms.BarnesStreakLegPoly2P1D(npts=(16, 10, 8, 4), zorder=8)

background = ilms.LegendrePoly2P1D(order=(7, 2, 2), category='bkg')

offset = comp.GlobalScalar(name='offset', value=0.)

from peri.comp import exactpsf

point_spread_function = exactpsf.FixedSSChebLinePSF()

from peri import models