def make_image_1(): P = objs.PlatonicSpheresCollection(pos, rad) H = psfs.AnisotropicGaussian() I = ilms.LegendrePoly3D(order=(5, 3, 3), constval=1.0) B = ilms.Polynomial3D(order=(3, 1, 1), category='bkg', constval=0.01) C = GlobalScalar('offset', 0.0) return states.ImageState(im, [B, I, H, P, C], pad=16, model_as_data=True)
def make_image_0(): P = objs.PlatonicSpheresCollection(pos, rad) H = psfs.AnisotropicGaussian() I = ilms.BarnesStreakLegPoly2P1D(npts=(20, 10), local_updates=True) B = GlobalScalar('bkg', 0.0) C = GlobalScalar('offset', 0.0) I.randomize_parameters() return states.ImageState(im, [B, I, H, P, C], pad=16, model_as_data=True)
def makestate(im, pos, rad, slab=None, mem_level='hi'): """ Workhorse for creating & optimizing states with an initial centroid guess. This is an example function that works for a particular microscope. For your own microscope, you'll need to change particulars such as the psf type and the orders of the background and illumination. Parameters ---------- im : :class:`~peri.util.RawImage` A RawImage of the data. 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. slab : :class:`peri.comp.objs.Slab` or None, optional If not None, a slab corresponding to that in the image. Default is None. mem_level : {'lo', 'med-lo', 'med', 'med-hi', 'hi'}, optional A valid memory level for the state to control the memory overhead at the expense of accuracy. Default is `'hi'` Returns ------- :class:`~peri.states.ImageState` An ImageState with a linked z-scale, a ConfocalImageModel, and all the necessary components with orders at which are useful for my particular test case. """ if slab is not None: o = comp.ComponentCollection( [ objs.PlatonicSpheresCollection(pos, rad, zscale=zscale), slab ], category='obj' ) else: o = objs.PlatonicSpheresCollection(pos, rad, zscale=zscale) p = exactpsf.FixedSSChebLinePSF() npts, iorder = _calc_ilm_order(im.get_image().shape) i = ilms.BarnesStreakLegPoly2P1D(npts=npts, zorder=iorder) b = ilms.LegendrePoly2P1D(order=(9 ,3, 5), category='bkg') c = comp.GlobalScalar('offset', 0.0) s = states.ImageState(im, [o, i, b, c, p]) runner.link_zscale(s) if mem_level != 'hi': s.set_mem_level(mem_level) opt.do_levmarq(s, ['ilm-scale'], max_iter=1, run_length=6, max_mem=1e4) return s
def create_state(image, pos, rad, slab=None, sigma=0.05, conf=conf_simple): """ Create a state from a blank image, set of pos and radii Parameters: ----------- image : `peri.util.Image` object raw confocal image with which to compare. pos : initial conditions for positions (in raw image coordinates) rad : initial conditions for radii array (can be scalar) sigma : float, noise level slab : float z-position of the microscope slide in the image (pixel units) """ # we accept radius as a scalar, so check if we need to expand it if not hasattr(rad, '__iter__'): rad = rad * np.ones(pos.shape[0]) model = models.models[conf.get('model')]() # setup the components based on the configuration components = [] for k, v in conf.get('comps', {}).iteritems(): args = conf.get('args').get(k, {}) comp = model.registry[k][v](**args) components.append(comp) sphs = objs.PlatonicSpheresCollection(pos, rad) if slab is not None: sphs = ComponentCollection([sphs, objs.Slab(zpos=slab + pad)], category='obj') components.append(sphs) s = states.ImageState(image, components, sigma=sigma) if isinstance(image, util.NullImage): s.model_to_data() return s
def create_img(): """Creates an image, as a `peri.util.Image`, which is similar to the image in the tutorial""" # 1. particles + coverslip rad = 0.5 * np.random.randn(POS.shape[0]) + 4.5 # 4.5 +- 0.5 px particles part = objs.PlatonicSpheresCollection(POS, rad, zscale=0.89) slab = objs.Slab(zpos=4.92, angles=(-4.7e-3, -7.3e-4)) objects = comp.ComponentCollection([part, slab], category='obj') # 2. psf, ilm p = exactpsf.FixedSSChebLinePSF(kfki=1.07, zslab=-29.3, alpha=1.17, n2n1=0.98, sigkf=-0.33, zscale=0.89, laser_wavelength=0.45) i = ilms.BarnesStreakLegPoly2P1D(npts=(16,10,8,4), zorder=8) b = ilms.LegendrePoly2P1D(order=(7,2,2), category='bkg') off = comp.GlobalScalar(name='offset', value=-2.11) mdl = models.ConfocalImageModel() st = states.ImageState(util.NullImage(shape=[48,64,64]), [objects, p, i, b, off], mdl=mdl, model_as_data=True) b.update(b.params, BKGVALS) i.update(i.params, ILMVALS) im = st.model + np.random.randn(*st.model.shape) * 0.03 return util.Image(im)
# 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') background = comp.ilms.LegendrePoly2P1D(order=(4,2,2), category='bkg') illumination = comp.ilms.BarnesStreakLegPoly2P1D(npts=(4, 2, 2)) offset = comp.GlobalScalar(name='offset', value=0.) point_spread_function = comp.exactpsf.ChebyshevLineScanConfocalPSF(pxsize=xpixel) model = models.ConfocalDyedParticlesModel() st = states.ImageState(small_im, [objects, illumination, background, point_spread_function], mdl=model) st.update('zscale', zscale) savefile = "/Volumes/PhD/expDesign/test/"+datetime.now().strftime("%Y%m%d-%H%M%S") + "_unoptimized" runner.link_zscale(st) runner.optimize_from_initial(st) savefile = "/Volumes/PhD/expDesign/test/"+datetime.now().strftime("%Y%m%d-%H%M%S") + "_inital_optimized" states.save(st,savefile) # new_st = runner.get_particles_featuring(8)
def locate_spheres(image, feature_rad, dofilter=False, order=(3, 3, 3), trim_edge=True, **kwargs): """ Get an initial featuring of sphere positions in an image. Parameters ----------- image : :class:`peri.util.Image` object Image object which defines the image file as well as the region. feature_rad : float Radius of objects to find, in pixels. This is a featuring radius and not a real radius, so a better value is frequently smaller than the real radius (half the actual radius is good). If ``use_tp`` is True, then the twice ``feature_rad`` is passed as trackpy's ``diameter`` keyword. dofilter : boolean, optional Whether to remove the background before featuring. Doing so can often greatly increase the success of initial featuring and decrease later optimization time. Filtering functions by fitting the image to a low-order polynomial and featuring the residuals. In doing so, this will change the mean intensity of the featured image and hence the good value of ``minmass`` will change when ``dofilter`` is True. Default is False. order : 3-element tuple, optional If `dofilter`, the 2+1D Leg Poly approximation to the background illumination field. Default is (3,3,3). Other Parameters ---------------- invert : boolean, optional Whether to invert the image for featuring. Set to True if the image is dark particles on a bright background. Default is True minmass : Float or None, optional The minimum mass/masscut of a particle. Default is None, which calculates internally. use_tp : Bool, optional Whether or not to use trackpy. Default is False, since trackpy cuts out particles at the edge. Returns -------- positions : np.ndarray [N,3] Positions of the particles in order (z,y,x) in image pixel units. Notes ----- Optionally filters the image by fitting the image I(x,y,z) to a polynomial, then subtracts this fitted intensity variation and uses centroid methods to find the particles. """ # We just want a smoothed field model of the image so that the residuals # are simply the particles without other complications m = models.SmoothFieldModel() I = ilms.LegendrePoly2P1D(order=order, constval=image.get_image().mean()) s = states.ImageState(image, [I], pad=0, mdl=m) if dofilter: opt.do_levmarq(s, s.params) pos = addsub.feature_guess(s, feature_rad, trim_edge=trim_edge, **kwargs)[0] return pos
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): plt.figure(figsize=[15, 6]) for i in xrange(3): plt.subplot(1, 3, 1 + i) mean_ax = tuple({0, 1, 2} - {i}) # which 2 directions to average over plt.plot(st.residuals.mean(axis=mean_ax)) plt.title('{}-averaged'.format(['$xy$', '$xz$', '$yz$'][i]), fontsize='large')
from peri import states, util, models from peri.comp import psfs, objs, ilms, GlobalScalar, ComponentCollection from peri.test import nbody import peri.opt.optimize as opt import peri.opt.addsubtract as addsub im = util.NullImage(shape=(32, ) * 3) pos, rad, tile = nbody.create_configuration(3, im.tile) P = ComponentCollection( [objs.PlatonicSpheresCollection(pos, rad), objs.Slab(2)], category='obj') H = psfs.AnisotropicGaussian() I = ilms.BarnesStreakLegPoly2P1D(npts=(25, 13, 3), zorder=2, local_updates=False) B = ilms.LegendrePoly2P1D(order=(3, 1, 1), category='bkg', constval=0.01) C = GlobalScalar('offset', 0.0) I.randomize_parameters() s = states.ImageState(im, [B, I, H, P, C], pad=16, model_as_data=True)