def diamondblur(a, sig): shifts = [array([-1*sig, 0]), array([0, -1*sig]), array([sig, 0]), array([0, sig])] ar = array([a] + map(lambda x:shiftarray(a, x), shifts)) ar = sum(ar).astype(Float64)/5 ar = ar.astype(a.dtype.char)+((ar%1)>0) return ar
def interpolate(self, tup): '''ind (sequence) => float or array of floats Acts like getitem, except uses linear interpolation based on the two nearest points to generate new points.''' inds = take(self.data.values, self.poll[0], 1) vals = take(self.data.values, self.poll[1], 1) if not type(tup)==ArrayType: tup=array(tup) d = eucd(tup, inds) neighbors = argsort(d)[:2] i=2 nbi=[0, 1] nb = inds[neighbors[0]],inds[neighbors[1]] while not all(nb[-1]-nb[0]): if i>=len(neighbors): return None nb[-1]=inds[neighbors[i]] nbi[1]=i i+=1 rel, offl = projectToLine(tup, nb[0], nb[1]) sep = eucd(nb[0],nb[1]) rel = rel/sep sv = vals[nbi[0]] change = vals[nbi[1]] - sv r = sv + change*rel if self.attrib("Grow") and self.attrib("Grow")!="False": newline = list(tup)+r.tolist() self.addEntry(array(newline)) if len(r)==1: return r[0] else: return r
def setPoll(self, li, lo): '''li (list of strs), lo (list of strs)=> [array, array] or None Arguments are sequences of labels. If all these are not in Labels, return False. Otherwise returns the attribute sell.poll (set to its new value). This is a list of two arrays of ints, corresponding to the column indexes of the labels in oi and lo. If return is not False, this method changes the behavior of __getitem__ and interpolate. By default these accept a list or array of values for the first M-1 columns, and return the value in the Mth column. This method causes the sampling methods to accept a sequence of values for the variables in li, and return values for the varriables in lo. If lo is len 1, a scalar value is returned. Otherwise an Nx1 array is returned where N is the len(lo).''' labels = self.data.getLabels() for e in li+lo: if not e in labels: return False self.poll =[[],[]] for e in li: self.poll[0].append(labels.index(e)) for e in lo: self.poll[1].append(labels.index(e)) self.poll = [array(self.poll[0]), array(self.poll[1])] return self.poll
def cache(self): """Create (or update) the cached values _pars, _ranges, _prec, _values. """ self._pars = [q.target() for q in self.elements] r = [] for q in self._pars: ra = q.attrib("Range") r.append([min(ra), max(ra) - min(ra)]) self._ranges = array(r) mp = self._ranges[:, 1] / 65535.0 self._prec = array([q.attrib("Precision") or 0.0 for q in self._pars]) self._prec = maximum(mp, self._prec) self._ints = nonzero1d(logical_not(logical_or(self._prec % 1, self._ranges[:, 0] % 1))) if any(self._prec > mp): ci = nonzero1d(self._prec > mp) cr = take(self._ranges[:, 0].ravel(), ci) cp = take(self._prec, ci) self._constrain = (ci, cr, cp) self._bins = (self._ranges[:, 1] / self._prec).astype(uint16) + 1 else: self._bins = ones(len(self._pars)) * 65535 self._bins = self._bins.astype(uint16) if any(self._bins < 2): id = nonzero1d(self._bins < 2)[0] p = self._pars[id] print "WARNING: ParameterSet member %s can not vary. Automatically Increasing range" % str(p) r = p.attrib("Range") minr = self._prec[id] p.setAttrib("Range", [r[0], r[0] + minr]) self.cache() return self._bits = None self._values = array([q.getValue() for q in self._pars])
def __getitem__(self, tup): '''ind (sequence) => float or array of floats Returns the value of the return column (the last entry in self.poll) for which the index columns (all entries but the last in self.poll) equal ind (or are within Granularity of ind). If there is no such value, return None. ''' inds = take(self.data.values, self.poll[0], 1) vals = take(self.data.values, self.poll[1], 1) if not type(tup)==ArrayType: tup=array(tup) ind = nonzero1d(alltrue(inds == tup, 1)) if len(ind): r=vals[ind[0]] if len(r)==1: return r[0] else: return r else: g=self.attrib("Granularity") if not g: return None else: g=float(g) d = eucd(tup, inds) a = argsort(d)[0] if d[a]<g: r = vals[a] if len(r)==1: return r[0] else: return r else: return None
def read(f): if type(f) in [str, unicode]: f=file(f, 'rb') l=f.read() l=re.split("[\r\n]+", l) dat = [] ls = l[0].split(',') try: dat.append(map(float, ls)) lab=None except: lab=ls llen = len(ls) l=l[1:] for line in l: ls = line.split(',') if len(ls)!=llen: print('Warning: encountered csv line of wrong length. Skipping line') continue try: dat.append(map(float, ls)) except: lls =[] for x in ls: try: lls.append(float(x)) except: lls.append(nan) dat.append(lls) dat=array(dat) return lab, dat
def windowedFFT(dat, fs): nfft = int(round(min(fs, dat.shape[0]))) nfft = min(16384, nfft) if nfft%2: nfft+=1 window = nfft/2 over = int(window/2) winstep = window-over nwin = int((dat.shape[0]-over)/winstep) if nwin < 1: nwin=1 window=inp.shape[0] over=0 hann=hanning(window) fts = [] for i in range(nwin): dsec=dat[i*winstep:i*winstep+window] dsec=(dsec-dsec.mean())*hann fts.append(rfft(dsec, nfft)) ft = array(fts).mean(0) freq = arange(ft.shape[0])*fs/(2.0*ft.shape[0]) amp = abs(ft) wfac = hann.sum()/hann.shape[0] amp*=2.0/(wfac*min(window, nfft)) phase = arctan2(ft.imag, ft.real) return (freq, amp, phase)
def make_indexedcolorscale(): a=arange(0,256) incr=7 a=a+1 b = array([x % incr for x in a]) rem = (a/7).astype(Int16) g=array([x % incr for x in rem]) rem = (rem/7).astype(Int16) r = array([x % incr for x in rem]) level=int(255.0/(incr-1)) r=(r)*level g=(g)*level b=(b)*level cspec=transpose(array([r,g,b])) colors=map(lambda x: wx.Colour(*tuple(x)), cspec) return colors
def get_drawing_coords(self, spheres=False): '''ref (bool=False) => array return a 2Nx3 (or 2Nx4) array containing the start and stop coordinates for each frustum specified in self.points.''' ord = self.branch() points = None for sn in self.branch(): s = self.getSection(sn) p =s.getPoints() if spheres and s.attrib("Spherical"): cent=sum(p)/p.shape[0] p=array([cent, cent]) p[1,3]=0.0 p[0,3]=float(s.attrib("Spherical")) else: s = p.shape p = concatenate([p, p],1) p = reshape(p.ravel(), (-1, s[1]))[1:-1] if p.shape[0] %2: print "Warning, %s has %i coords" % (sn, p.shape[0]) if points == None: points = p else: try: points = concatenate([points, p]) except: print points.shape, p.shape raise return points
def changesize(self, newshape, insertat, optimize = True): new = Sparse(None, newshape) dat = self.sparse() dat[0] = dat[0] + array(insertat) new.set(dat) if optimize: new.squeeze() return new
def alphaColor(c, ap): a=array(c) l=list(c) z=[0,0,0] glMaterial(GL_FRONT_AND_BACK, GL_AMBIENT, l+[ap]) glMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE, z+[ap]) glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, z+[ap]) glMaterial(GL_FRONT_AND_BACK, GL_SHININESS, 0.0)
def sample(self, n): '''n(int) => n x 4 array of floats returns an array of points generated drawing n equally spaced absolute locations along the section (0 is always sampled. 1 is never sampled).''' step = 1.0/n pts=arange(0, 1, step) locs = map(self.absoluteLocation, pts) return array(locs)
def materialColor(c): a=array(c) amb=a/4.0 dif=a/2.0 glMaterial(GL_FRONT_AND_BACK, GL_AMBIENT, amb.tolist()+[1.0]) glMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE, dif.tolist()+[1.0]) glMaterial(GL_FRONT_AND_BACK, GL_SPECULAR, a.tolist()+[1.0]) glMaterial(GL_FRONT_AND_BACK, GL_SHININESS, 10.0)
def makeFade(rgb): a=arange(0,1.0003, 1.0/255) r=(rgb[0]*a).astype('b') g=(rgb[1]*a).astype('b') b=(rgb[2]*a).astype('b') cspec=transpose(array([r,g,b])) colors=map(tuple, cspec) colors = map(lambda x: wx.Colour(*x), colors) return colors
def getCM(a): i=indices(a.shape) tw=a.sum() dw=a*i x=dw[0].sum()/tw y=dw[1].sum()/tw z=dw[2].sum()/tw loc=array([x,y,z])*EDGE+ORIGIN return tuple(loc)
def make_hotcolorscale(): a=arange(0,100.3, 100.0/255) r=convert_type(255/(1.0 + exp(-1*(a-50)/2.0)), 'B') g=convert_type(255*exp(-.5*(((a-45)/10)**2))+r*exp(-.4*(100-a)), 'B') b=convert_type(255*exp(-.5*(((a-20)/10)**2))+r*exp(-.4*(100-a)), 'B') cspec=transpose(array([r,g,b])) colors=map(tuple, cspec) colors = map(lambda x: wx.Colour(*x), colors) return colors
def makeFade(rgb): a=arange(0,1.0003, 1.0/255) r=(rgb[0]*a).astype('B') g=(rgb[1]*a).astype('B') b=(rgb[2]*a).astype('B') cspec=transpose(array([r,g,b])) cspec=cspec.astype(Float32)/255 colors=map(tuple, cspec) return colors
def calculate(self, tup): '''tup (tuple) => float evaluate child function using input tuple.''' f = self.getElements("Function", {}, 1)[0] out = f[tup] if self.attrib("Grow") and self.attrib("Grow")!="False": newline = list(tup)+[out] self.addEntry(array(newline)) return out
def scalePoints(conv, a, diams): scale = array([conv.get("Scale_x", 1.0), conv.get("Scale_y", 1.0), conv.get("Scale_z", 1.0)]) if any(scale!=1): scale = resize(scale, a.shape) a = a*scale if diams!=None: sd = conv.get("Scale_d", 1.0) if sd!=1.0: diams = diams*sd return (a, diams)
def drawFromHist(n, a): '''return n samples drawn from probabilities specified in array a. A is first scaled to act as a probability distribution (a=a/a.sum()). Return vaules are the integers and index a (e.g. a "3" represents an event of the type in histogram bin a[3]).''' pd=a/float(a.sum()) pd=cumsum(pd) evts=uniform(0, 1, n) indexes=array([(pd<=e).sum() for e in evts]) return indexes
def addEvents(self, t, ind=-1): '''t (array of floats), ind (int) => None Adds events at times specified in t to the event list for synapse index ind''' t=array(t) ti=round(t*self.data.fs()) if self.data.attrib('SampleType')=='events': ti=reshape(ti, (-1,1)) else: ti=column_stack([ti, ones_like(ti)*ind]) self.data.concat(ti)
def neighbors(a, r): if r==0: return a.copy() sl = transpose(array([concatenate([arange(-r,1),arange(0,r+1)]), concatenate([arange(0,-r-1,-1),arange(r,-1,-1)])])) n = zeros(a.shape, Float64) for i in range(sl.shape[0]): n+=shiftarray(a,sl[i]) n = n.astype(Float64)/sl.shape[0] return n
def splitAtRel(self, loc): '''loc (relative location) => None''' print self.upath() if loc in [0.0, 1.0]: self.report("This is already a section edge") return node=self.getTree(recurse=0) node['attributes']['Name']=self.container.newSectionName() print self.upath() newparent = Section(node) for k in ["Ra"]: if self.attrib(k): newparent.attributes[k]=self.attrib(k) self.attributes["Parent"]=newparent.name() points = self.getPoints() sp = self.absoluteLocation(loc) pid = self.ptAtRel(loc) if all(points[pid] == sp): print "Exact" spts = points[pid:,:] ppts = points[:pid+1,:] else: spts = points[pid:,:] spts = concatenate([array([sp]), spts]) ppts = points[:pid,:] ppts = concatenate([ppts, array([sp])]) newparent.setPoints(ppts) self.setPoints(spts) for e in self.elements: if e.__tag__=="Synapse": synpt = int(e.attrib("Point")) if synpt < pid: newparent.newElement(e) print "moved %s" % str(e) else: synpt = synpt - pid e.attributes["Point"]=synpt else: newparent.newElement(e.clone()) self.container.newElement(newparent) print self.upath()
def coherence(idat, odat, fs): '''idat (1D array), odat (1D array), fs (sampling freq in Hz) => 2D array (coherence estimate)''' nfft=2**int(log(fs)/log(2)) #Try and match this to fs (16384 at 20KHz) while nfft>idat.shape[0]: nfft=nfft/2 Pxx, Pyy, Pxy=getSpectraHann(idat, odat, nfft) freq = arange(Pxx.shape[0]).astype(Float64)*fs/(2*Pxx.shape[0]) coh = abs(Pxy)**2/(Pxx*Pyy) fcd = transpose(array([freq, coh])) return fcd
def convertColor(c, mode='py'): try: if type(c)==ColorType: pass elif type(c) in [str, unicode]: c=apply(wx.Colour, c) elif type(c) in [tuple, list]: c=array(c) if all(c>=0.0) and all(c<=1.0): c=c*255 c=apply(wx.Colour, c) except: print c raise print "can't identify color" c=wx.Colour(255,255,255) if mode=='gl': c=c.Get() c=tuple(array(c)/255.0) elif mode=='py': c=c.Get() return c
def getSectionBoundaries(self): '''-> array return an array containing the ening points of each section (in the order used by self.branch()). The first element is the starting point of the root section (all other sections should start where their parent ends)''' pts=[] r= self.getSection(self.root()) pts.append(r.points[0]) for sn in self.branch(): s = self.getSection(sn) pts.append(s.points[-1]) return array(pts)
def refresh(self): self._instance_references = {} self.findDataElement() labels = self.data.attrib("Labels").split(',') self.setPoll(labels[:-1], [labels[-1]]) if 'x' in labels and 'y' in labels and 'z' in labels: self.spatial=[] for k in ['x','y','z']: self.spatial.append(labels.index(k)) if 'd' in labels: self.spatial.append(labels.index('d')) self.spatial = array(self.spatial) else: self.spatial = None
def resize(self, event=None): d=self.askParam([{"Name":"Duration(sec)", "Value": self.duration}, {"Name":"Sampling Rate(Hz)", "Value":1.0/self.sampling}]) if not d: return self.duration=d[0] self.sampling=1.0/d[1] for s in range(len(self.channels)): self.channels[s].set_domain((0, self.duration, self.sampling)) self.report("New duration: %.5f s, New sampling: %.3f Hz" % (self.duration, 1/self.sampling)) xp = self.duration*.05 self.graph.limit(array([-xp, self.duration+xp, -2, 2])) self.display()
def compartmentCenters(self): '''No Args: returns a list of [sec, [p1 p2 p3]] contianing the name of each section and the list of relative locations at the center of each compartment in the section''' sl=[] for sn in self.branch(): sec = self.getSection(sn) ind=sec.points.shape[0] rels=[] for i in range(ind): rels.append(sec.relLocOfPtN(i)) rels=array(rels) rels=(rels[:-1]+rels[1:])/2 rels=list(rels) sl.append([sn, rels]) return sl
def densityEstimate(dat, gw=7.0): '''dat (Nx4 array), gw (float=7.0) -> array (of size EXTENT) of floats) Estimate the density of points in dat, using the Theunissen 1996 method with a fixed gaussian width of gw (in microns). Sample this estimate in a grid of (extent) voxels with side length (edge) microns anchored at (origin). Return an array of the samples''' est=zeros(EXTENT, Float64) for xi in range(EXTENT[0]): print xi for yi in range(EXTENT[1]): for zi in range(EXTENT[2]): x=EDGE*xi+ORIGIN[0] y=EDGE*yi+ORIGIN[1] z=EDGE*zi+ORIGIN[2] pt=array([x,y,z]) est[xi,yi,zi]=dContrib(dat, pt, gw) print est.max() return est