def _construct_zmodes_from_mask(self, wfs_raw): # get the pupil shape and center from the data # crop inds = np.where(np.isnan(wfs_raw[0])) wfs = wfs_raw[:, np.amin(inds[0]):np.amax(inds[0]), np.amin(inds[1]):np.amax(inds[1])] # find center/pupil pupil = np.bitwise_not(np.isnan(wfs[0])) pupil_sum = np.sum(pupil) _Y, _X = np.meshgrid(np.arange(wfs[0].shape[0]), np.arange(wfs[0].shape[1]), indexing="ij") y0, x0 = 1. * np.sum(_Y * pupil) / pupil_sum, 1. * np.sum( _X * pupil) / pupil_sum rad = np.sqrt(pupil_sum / np.pi) _R = np.sqrt((_X - x0)**2 + (_Y - y0)**2) / rad _P = np.arctan2(_Y - y0, _X - x0) self._wf_dx = 1. / rad self.zern_modes_wf = np.stack([ 1. / np.sqrt(np.pi) * zernike(n, m, _R, _P) for n, m in self.zmodes_alpao_order[:self.n_custom_modes] ]) self._wfs = wfs
def __init__(self, fname=""): if fname: self.load(fname) self.acc_coords = self.actuator_coords() _x = np.linspace(-1, 1, 100) Y, X = np.meshgrid(_x, _x, indexing="ij") rho = np.hypot(X, Y) phi = np.arctan2(Y, X) self.zern_modes = np.stack( [zernike(n, m, rho, phi) for n, m in self.zmodes_alpao_order]) for z in self.zern_modes: z[rho > 1] = np.nan Y, X = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6), indexing="ij") self.accs_mask = np.bitwise_and( np.bitwise_and(-X - 1 + Y - 1 < 6, X - 1 + Y - 1 < 6), np.bitwise_and(X - 1 - Y - 1 < 6, -X - 1 - Y - 1 < 6))
def computefeatures(img, featsets, progress=None, preprocessing=None, **kwargs): """ features = computefeatures(img,featsets,progress=None,**kwargs) Compute features defined by featsets on image img. featsets can be either a list of feature groups. Feature groups: -------------- + 'har': 13 Haralick features [in matslic] + 'har3d': 26 Haralick features (actually this works in 2D as well) + 'skl': Skeleton features [in matslic] (syn: 'skel') + 'img': Image features [in matslic] + 'hul': Hull features [in matslic] (syn: 'hull') + 'edg': Edge features [in matslic] (syn: 'edge') + 'zer': Zernike moments [in matslic] + 'tas' : Threshold Adjacency Statistics + 'pftas' : Parameter-free Threshold Adjacency Statistics Feature set names: + 'SLF7dna' + 'mcell': field level features + 'field+': all field level features. The exact exact number of features computed is liable to change (increase) in newer versions img can be a list of images. In this case, a two-dimensional feature vector will be returned, where f[i,j] is the j-th feature of the i-th image. Also, in this case, imgs will be unload after feature calculation. Parameters ---------- * *progress*: if progress is not None, then it should be an integer. Every *progress* images, an output message will be printed. * *preprocessing*: Whether to do preprocessing (default: True). If False and img.channeldata[procprotein|procdna] are empty, they are filled in using img.channeldata[protein|dna] respectively. * *options*: currently passed through to pyslic.preprocessimage """ if type(featsets) == str: featsets = _featsfor(featsets) if type(img) == list: features = [] for i, im in enumerate(img): f = computefeatures(im, featsets, progress=None, **kwargs) features.append(f) im.unload() if progress is not None and (i % progress) == 0: print "Processed %s images..." % i return numpy.array(features) regions = img.regions if regions is not None and regions.max() > 1 and "region" not in kwargs: precomputestats(img) return numpy.array( [ computefeatures(img, featsets, progress=progress, region=r, **kwargs) for r in xrange(1, regions.max() + 1) ] ) scale = img.scale if scale is None: scale = _Default_Scale is_surf = len(featsets) == 1 and featsets[0] in ("surf", "surf-ref", "surfp") if preprocessing is None: preprocessing = not is_surf if preprocessing: preprocessimage(img, kwargs.get("region"), options=kwargs.get("options", {})) else: if "procprotein" not in img.channeldata: img.channeldata["procprotein"] = img.get("protein") img.channeldata["resprotein"] = 0 * img.get("protein") if ("dna" in img.channeldata) and ("procdna" not in img.channeldata): img.channeldata["procdna"] = img.get("dna") features = numpy.array([]) protein = img.get("protein") procprotein = img.get("procprotein") resprotein = img.get("resprotein") dna = img.channeldata.get("dna") procdna = img.channeldata.get("procdna") if procprotein.size < _Min_image_size: if is_surf: return np.array([]) if featsets == _featsfor("SLF7dna"): return np.array([np.nan for i in xrange(90)]) if featsets == _featsfor("field-dna+"): return np.array([np.nan for i in xrange(173)]) raise ValueError lbppat = re.compile(r"lbp\(([0-9]+), ?([0-9]+)\)") for F in featsets: if F in ["edg", "edge"]: feats = edgefeatures(procprotein) elif F == "raw-har": feats = haralickfeatures(procprotein).mean(0) elif F[:3] == "har": img = procprotein har_scale = kwargs.get("haralick.scale", _Default_Haralick_Scale) if F == "har" and scale != har_scale: img = img.copy() img = ndimage.zoom(img, scale / _Default_Haralick_Scale) if len(F) > 3: rate = int(F[3]) if rate != 1: C = np.ones((rate, rate)) img = np.array(img, np.uint16) img = ndimage.convolve(img, C) img = img[::rate, ::rate] if not img.size: feats = np.zeros(13) else: bins = kwargs.get("haralick.bins", _Default_Haralick_Bins) if bins != 256: min = img.min() max = img.max() ptp = max - min if ptp: img = np.array((img - min).astype(float) * bins / ptp, np.uint8) feats = haralickfeatures(img) feats = feats.mean(0) elif F in ["hul", "hull"]: feats = hullfeatures(procprotein) elif F == "hullsize": feats = hullsizefeatures(procprotein) elif F == "hullsizedna": feats = hullsizefeatures(procdna) elif F == "img": feats = imgfeaturesdna(procprotein, procdna) elif F in ("obj-field", "obj-field-dna"): feats = imgfeaturesdna(procprotein, procdna, isfield=True) elif F == "mor": feats = morphologicalfeatures(procprotein) elif F == "nof": feats = noffeatures(procprotein, resprotein) elif F in ["skl", "skel"]: feats = imgskelfeatures(procprotein) elif F == "zer": feats = zernike(procprotein, 12, 34.5, scale) elif F == "tas": feats = tas(protein) elif F == "pftas": feats = pftas(procprotein) elif F == "overlap": feats = overlapfeatures(protein, dna, procprotein, procdna) elif lbppat.match(F): radius, points = lbppat.match(F).groups() feats = lbp(protein, int(radius), int(points)) elif F in ("surf", "surf-ref", "surfp"): if F == "surfp": from warnings import warn warn("surfp is deprecated. Use surf-ref", DeprecationWarning) if len(featsets) > 1: raise ValueError("pyslic.features.computefeatures: surf-ref must be computed on its own") if F == "surf": dna = None return surf_ref(protein, dna) else: raise Exception("Unknown feature set: %s" % F) features = numpy.r_[features, feats] return features
# fit functions #---------------------------------------------------------------------- def Em_pow(x): # simple power law s = alpha() * x**lam() return s def Em_pol(x): # simple polynomial s = p0() + p1() * x + p2() * x**2 + p3() * x**3 + p4() * x**4 + p5() * x**5 return s #---------------------------------------------------------------------- z20 = Z.zernike(2, 0) z40 = Z.zernike(4, 0) z60 = Z.zernike(6, 0) z80 = Z.zernike(8, 0) z100 = Z.zernike(10, 0) #---------------------------------------------------------------------- def Em_zern(x): # zernike polynmials with m = 0 s = p0() + p1() * z20(x, 0.) + p2() * z40(x, 0.) + p3() * z60( x, 0.) + p4() * z80(x, 0.) + p5() * z100(x, 0.) return s
#---------------------------------------------------------------------- def Em_pol_sq(x): # simple polynomial s = (p0() + p1() * x + p2() * x**2 + p3() * x**3)**2 return s def Em_pol_sq_der(x): s = (p0() + p1() * x + p2() * x**2 + p3() * x**3) return np.array([np.ones_like(x), x, x**2, x**3]) * 2. * s #---------------------------------------------------------------------- z1m1 = Z.zernike(1, -1) z1p1 = Z.zernike(1, 1) z20 = Z.zernike(2, 0) z2m2 = Z.zernike(2, -2) z2p2 = Z.zernike(2, 2) z3m3 = Z.zernike(3, -3) z3m1 = Z.zernike(3, -1) z3p1 = Z.zernike(3, 1) z3p3 = Z.zernike(3, 3) z40 = Z.zernike(4, 0) z60 = Z.zernike(6, 0) z80 = Z.zernike(8, 0) z100 = Z.zernike(10, 0) #---------------------------------------------------------------------- # Zernike polynomials
def zernike_mask(rs, n, m): _R = 1. / 5 * np.sqrt(np.sum(rs**2, axis=1)) _P = np.arctan2(rs[:, 0], rs[::-1, 1]) return zernike(n, m, _R, _P)
"""Defining the input field""" win = 2e-3 x0, N = 40*win, 2**14 x = np.linspace(-x0, x0, N) E_ref = EField(x, gaussian(x, 1, 0*win, win, 0), lda=771e-9, normalize=True) # E_ref = HG_efield(n=0, x=x, w=win, amplitude=1.0, x0=0*win, # normalize=True, lda=771e-9) # E_ref += HG_efield(n=0, x=x, w=win, amplitude=1.0, x0=0.0, # normalize=True, lda=771e-9) E_in = E_ref.tilt(0e-4) r_zernike = 3e-3 u = x / r_zernike phase_map = np.zeros(u.size) phase_map[abs(u) < 1.0] = zernike.zernike(4, 0, 5.0, abs(u[abs(u) < 1.0])) # cavity.insert(2, interfaces.PhaseMask(phase_map)) """Computation""" N_rt = int(2*cavity.finess) with Timer() as t_fields: handler.calculate_fields(E_in, N=N_rt) with Timer() as t_lock: phases_lock = handler.lock_cavity() dp = 2*np.pi/20 phases = utils.focused_linspace(min(0, min(phases_lock)), max(2*np.pi, max(phases_lock)),
def computefeatures(img, featsets, progress=None, preprocessing=True, **kwargs): ''' features = computefeatures(img,featsets,progress=None,**kwargs) Compute features defined by featsets on image img. featsets can be either a list of feature groups. Feature groups: -------------- + 'har': 13 Haralick features [in matslic] + 'har3d': 26 Haralick features (actually this works in 2D as well) + 'skl': Skeleton features [in matslic] (syn: 'skel') + 'img': Image features [in matslic] + 'hul': Hull features [in matslic] (syn: 'hull') + 'edg': Edge features [in matslic] (syn: 'edge') + 'zer': Zernike moments [in matslic] + 'tas' : Threshold Adjacency Statistics + 'pftas' : Parameter-free Threshold Adjacency Statistics Feature set names: + 'SLF7dna' + 'mcell': field level features + 'field+': all field level features. The exact exact number of features computed is liable to change (increase) in newer versions img can be a list of images. In this case, a two-dimensional feature vector will be returned, where f[i,j] is the j-th feature of the i-th image. Also, in this case, imgs will be unload after feature calculation. Parameters ---------- * *progress*: if progress is not None, then it should be an integer. Every *progress* images, an output message will be printed. * *preprocessing*: Whether to do preprocessing (default: True). If False and img.channeldata[procprotein|procdna] are empty, they are filled in using img.channeldata[protein|dna] respectively. * *options*: currently passed through to pyslic.preprocessimage ''' if type(featsets) == str: featsets = _featsfor(featsets) if type(img) == list: features=[] for i,im in enumerate(img): f = computefeatures(im,featsets,progress=None,**kwargs) features.append(f) im.unload() if progress is not None and (i % progress) == 0: print 'Processed %s images...' % i return numpy.array(features) regions = img.regions if regions is not None and regions.max() > 1 and 'region' not in kwargs: precomputestats(img) return numpy.array([ computefeatures(img, featsets, progress=progress, region=r, **kwargs) for r in xrange(1,regions.max()+1)]) scale = img.scale if scale is None: scale = _Default_Scale if preprocessing: preprocessimage(img, kwargs.get('region',1), options=kwargs.get('options',{})) else: if not img.channeldata['procprotein']: img.channeldata['procprotein'] = img.get('protein') img.channeldata['resprotein'] = 0*img.get('protein') if not img.channeldata['procdna']: img.channeldata['procdna'] = img.get('dna') features = numpy.array([]) protein = img.get('protein') procprotein = img.get('procprotein') resprotein = img.get('resprotein') dna = img.channeldata.get('dna') procdna = img.channeldata.get('procdna') if procprotein.size < _Min_image_size: return np.array([np.nan for i in xrange(90)]) lbppat = re.compile(r'lbp\(([0-9]+), ?([0-9]+)\)') for F in featsets: if F in ['edg','edge']: feats = edgefeatures(procprotein) elif F == 'raw-har': feats = haralickfeatures(procprotein).mean(0) elif F[:3] == 'har': img = procprotein har_scale = kwargs.get('haralick.scale',_Default_Haralick_Scale) if F == 'har' and scale != har_scale: img = img.copy() img = ndimage.zoom(img, scale/_Default_Haralick_Scale) if len(F) > 3: rate = int(F[3]) if rate != 1: C = np.ones((rate,rate)) img = np.array(img,np.uint16) img = ndimage.convolve(img,C) img = img[::rate,::rate] if not img.size: feats = np.zeros(13) else: bins = kwargs.get('haralick.bins',_Default_Haralick_Bins) if bins != 256: min = img.min() max = img.max() ptp = max - min if ptp: img = np.array((img-min).astype(float) * bins/ptp, np.uint8) feats = haralickfeatures(img) feats = feats.mean(0) elif F == 'har3d': feats = haralickfeatures(procprotein) feats = numpy.r_[feats.mean(0),feats.ptp(0)] elif F in ['hul', 'hull']: feats = hullfeatures(procprotein) elif F == 'hullsize': feats = hullsizefeatures(procprotein) elif F == 'hullsizedna': feats = hullsizefeatures(procdna) elif F == 'img': feats = imgfeaturesdna(procprotein, procdna) elif F in ('obj-field', 'obj-field-dna'): feats = imgfeaturesdna(procprotein, procdna, isfield=True) elif F == 'mor': feats = morphologicalfeatures(procprotein) elif F == 'nof': feats = noffeatures(procprotein,resprotein) elif F in ['skl', 'skel']: feats = imgskelfeatures(procprotein) elif F == 'zer': feats = zernike(procprotein,12,34.5,scale) elif F == 'tas': feats = tas(protein) elif F == 'pftas': feats = pftas(procprotein) elif F == 'overlap': feats = overlapfeatures(protein, dna, procprotein, procdna) elif lbppat.match(F): radius,points = lbppat.match(F).groups() feats = lbp(protein, int(radius), int(points)) else: raise Exception('Unknown feature set: %s' % F) features = numpy.r_[features,feats] return features