def decodefft(finf, data, dropheights=False): #output: decoded data with the number of heights reduced #two variables are added to the finfo class: #deco_num_hei, deco_hrange #data must be arranged: # (channels,heights,times) (C-style, profs change faster) #fft along the entire(n=None) acquired heights(axis=1), stores in data num_chan = data.shape[0] num_ipps = data.shape[2] num_codes = finf.subcode.shape[0] num_bauds = finf.subcode.shape[1] NSA = finf.num_hei + num_bauds - 1 uppower = py.ceil(py.log2(NSA)) extra = int(2**uppower - finf.num_hei) NSA = int(2**uppower) fft_code = py.fft(finf.subcode, n=NSA, axis=1).conj() data = py.fft(data, n=NSA, axis=1) #n= None: no cropped data or padded zeros for ch in range(num_chan): for ipp in range(num_ipps): code_i = ipp % num_codes data[ch, :, ipp] = data[ch, :, ipp] * fft_code[code_i, :] data = py.ifft(data, n=NSA, axis=1) #fft along the heightsm if dropheights: return data[:, :-extra - (num_bauds - 1), :] else: return data[:, :-extra, :]
def decodefft(finf,data, dropheights = False): #output: decoded data with the number of heights reduced #two variables are added to the finfo class: #deco_num_hei, deco_hrange #data must be arranged: # (channels,heights,times) (C-style, profs change faster) #fft along the entire(n=None) acquired heights(axis=1), stores in data num_chan = data.shape[0] num_ipps = data.shape[2] num_codes = finf.subcode.shape[0] num_bauds = finf.subcode.shape[1] NSA = finf.num_hei + num_bauds - 1 uppower = py.ceil(py.log2(NSA)) extra = int(2**uppower - finf.num_hei) NSA = int(2**uppower) fft_code = py.fft(finf.subcode,n = NSA,axis=1).conj() data = py.fft(data,n=NSA,axis=1) #n= None: no cropped data or padded zeros for ch in range(num_chan): for ipp in range(num_ipps): code_i = ipp % num_codes data[ch,:,ipp] = data[ch,:,ipp] * fft_code[code_i,:] data=py.ifft(data,n=NSA,axis=1) #fft along the heightsm if dropheights: return data[:,:-extra-(num_bauds-1),:] else: return data[:,:-extra,:]
def show_blocking(self, plotfile=''): '''Print out the blocking data and show a graph of the behaviour of the standard error with block size. If plotfile is given, then the graph is saved to the specifed file rather than being shown on screen.''' # print blocking output # header... print '%-11s' % ('# of blocks'), fmt = '%-14s %-15s %-18s ' header = ('mean (X_%i)', 'std.err. (X_%i)', 'std.err.err. (X_%i)') for data in self.data: data_header = tuple(x % (data.data_col) for x in header) print fmt % data_header, for key in self.covariance: str = 'cov(X_%s,X_%s)' % tuple(key.split(',')) print '%-14s' % (str), for key in self.combination_stats: fmt = ['mean (X_%s'+self.combination+'X_%s)', 'std.err. (X_%s'+self.combination+'X_%s)'] strs = tuple([s % tuple(key.split(',')) for s in fmt]) print '%-16s %-18s' % strs, print # data block_fmt = '%-11i' fmt = '%-#14.12g %-#12.8e %-#18.8e ' for s in range(len(self.data[0].stats)): print block_fmt % (self.data[0].stats[s].block_size), for data in self.data: print fmt % (data.stats[s].mean, data.stats[s].se, data.stats[s].se_error), for cov in self.covariance.itervalues(): print '%+-#14.5e' % (cov[s]), for comb in self.combination_stats.itervalues(): print '%-#16.12f %-#18.12e' % (comb[s].mean, comb[s].se), print # plot standard error if PYLAB: # one sub plot per data set. nplots = len(self.data) for (i, data) in enumerate(self.data): pylab.subplot(nplots, 1, i+1) blocks = [stat.block_size for stat in data.stats] se = [stat.se for stat in data.stats] se_error = [stat.se_error for stat in data.stats] pylab.semilogx(blocks, se, 'g-', basex=2, label=r'$\sigma(X_{%s})$' % (data.data_col)) pylab.errorbar(blocks, se, yerr=se_error, fmt=None, ecolor='g') xmax = 2**pylab.ceil(pylab.log2(blocks[0]+1)) pylab.xlim(xmax, 1) pylab.ylabel('Standard error') pylab.legend(loc=2) if i != nplots - 1: # Don't label x axis points. ax = pylab.gca() ax.set_xticklabels([]) pylab.xlabel('# of blocks') if plotfile: pylab.savefig(plotfile) else: pylab.draw() pylab.show()
def main(): print 'Welcome to ProblemSet0' x = get_input('Enter value for value x: ') y = get_input('Enter value for value y: ') z = exponant(x, y) print 'x**y = {}'.format(z) print 'logx = {}'.format(log(x)) # with numpy print 'logx = {}'.format(pylab.log2(x)) # with pylab
def circular_conv(x,h): P = len(h) n_ = int(ceil(log2(P))) h_ = np.concatenate((h,np.zeros(int(2**n_)-P))) P = len(h_) n1 = int(ceil(len(x)/2**n_)) x_ = np.concatenate((x,np.zeros(n1*(int(2**n_))-len(x)))) y = np.zeros(len(x_)+len(h_)-1) for i in range(n1): temp = np.concatenate((x_[i*P:(i+1)*P],np.zeros(P-1))) y[i*P:(i+1)*P+P-1] += np.fft.ifft(np.fft.fft(temp)*np.fft.fft(np.concatenate((h_,np.zeros(len(temp)-len(h_)))))).real return y
def expFit(x, y): """ Find the best fit exponential curve z for the data contained in x and y. Parameters: x - a Pylab array of x values y - a Pylab array of y values Returns: a Pylab array of coefficients for the exponential fit function corresponding to the input domain x. """ y = pylab.log2(y) return pylab.polyfit(x, y, 1)
def nextpower(x): """Returns next power of 2 times 2 :: >>> nextpower(9) 32 >>> nextpower(16) 32 >>> nextpower(17) 64 """ return int(2**(math.ceil(pylab.log2(x)) + 1 ))
def expFit(x, y): """ Find the best fit exponential curve z for the data contained in x and y. Parameters: x - a Pylab array of x values y - a Pylab array of y values Returns: a Pylab array of coefficients for the exponential fit function corresponding to the input domain x. """ y = pylab.log2(y) return pylab.polyfit(x,y,1)
def mi(x,y, bins=11): """Given two arrays x and y of equal length, return their mutual information in bits """ Hxy, xe, ye = pylab.histogram2d(x,y,bins=bins) Hx = Hxy.sum(axis=1) Hy = Hxy.sum(axis=0) Pxy = Hxy/float(x.size) Px = Hx/float(x.size) Py = Hy/float(x.size) pxy = Pxy.ravel() px = Px.repeat(Py.size) py = pylab.tile(Py, Px.size) idx = pylab.find((pxy > 0) & (px > 0) & (py > 0)) return (pxy[idx]*pylab.log2(pxy[idx]/(px[idx]*py[idx]))).sum()
def ifft(s): N = len(s) sig = reorder(s) logN = int(pl.log2(N)) for n in [2**x for x in range(0, logN)]: o = -pl.pi / n wp = pl.cos(o) + pl.sin(o) * 1j w = 1 + 0j for m in range(0, n): for k in range(m, N, n * 2): i = k + n even, odd = sig[k], w * sig[i] sig[k] = even + odd sig[i] = even - odd w *= wp return sig
def genIm(self, dlg, imb, mdh): pixelSize = dlg.getPixelSize() if not pylab.mod(pylab.log2(pixelSize/self.visFr.QTGoalPixelSize), 1) == 0:#recalculate QuadTree to get right pixel size self.visFr.QTGoalPixelSize = pixelSize self.visFr.Quads = None self.visFr.GenQuads() qtWidth = self.visFr.Quads.x1 - self.visFr.Quads.x0 qtWidthPixels = pylab.ceil(qtWidth/pixelSize) im = pylab.zeros((qtWidthPixels, qtWidthPixels)) QTrend.rendQTa(im, self.visFr.Quads) return im[(imb.x0/pixelSize):(imb.x1/pixelSize),(imb.y0/pixelSize):(imb.y1/pixelSize)]
def __init__(self, X0, X1, pvalue=None, intensity=None): """data should be a time series/numpy array or whatever can be converted to 1D list. The data should be log2 fold change fold change depends on intensity (if you don't have a p-value), as there is more vairability at low intensities, so always keep an eye on the intensity as well as the fold change. Sort them by fold change, but have the average intensity on the side. A fold change of 3 but very low intensity is not very reliable... """ self.fold_change = pylab.log2(X1 / X0) self.pvalue = pvalue if pvalue == None: # assume a normal distribution mean 0 and sigma 1 import scipy.stats self.pvalue = -pylab.log10( scipy.stats.norm.pdf(abs(self.fold_change), 0, 1)), self.intensity = intensity if self.intensity is None: self.intensity = intensity
def mutual_information(x,y, bins=11): """Given two arrays x and y of equal length, return their mutual information in bits >>> N = 10000 >>> xi = pylab.randn(N) >>> xi[pylab.find(xi>0)] = 1 >>> xi[pylab.find(xi<=0)] = 0 >>> yi = xi >>> print round(mutual_information(xi, yi, 1000),2) #One bit of info 1.0 >>> N = 10000 >>> xi = pylab.uniform(size=N) >>> yi = pylab.floor(xi*8) >>> print round(mutual_information(xi, yi, 1000),2) #Three bits of info 3.0 >>> N = 100000 >>> xi = pylab.randn(N) >>> yi = pylab.randn(N) >>> print round(mutual_information(xi, yi),2) #Should be zero given enough data and not too sparse binning 0.0 """ Hxy, xe, ye = pylab.histogram2d(x,y,bins=bins) Hx = Hxy.sum(axis=1) Hy = Hxy.sum(axis=0) Pxy = Hxy/float(x.size) Px = Hx/float(x.size) Py = Hy/float(x.size) pxy = Pxy.ravel() px = Px.repeat(Py.size) py = pylab.tile(Py, Px.size) idx = pylab.find((pxy > 0) & (px > 0) & (py > 0)) mi = (pxy[idx]*pylab.log2(pxy[idx]/(px[idx]*py[idx]))).sum() return mi
def mutual_information(x, y, bins=11): """Given two arrays x and y of equal length, return their mutual information in bits >>> N = 10000 >>> xi = pylab.randn(N) >>> xi[pylab.find(xi>0)] = 1 >>> xi[pylab.find(xi<=0)] = 0 >>> yi = xi >>> print round(mutual_information(xi, yi, 1000),2) #One bit of info 1.0 >>> N = 10000 >>> xi = pylab.uniform(size=N) >>> yi = pylab.floor(xi*8) >>> print round(mutual_information(xi, yi, 1000),2) #Three bits of info 3.0 >>> N = 100000 >>> xi = pylab.randn(N) >>> yi = pylab.randn(N) >>> print round(mutual_information(xi, yi),2) #Should be zero given enough data and not too sparse binning 0.0 """ Hxy, xe, ye = pylab.histogram2d(x, y, bins=bins) Hx = Hxy.sum(axis=1) Hy = Hxy.sum(axis=0) Pxy = Hxy / float(x.size) Px = Hx / float(x.size) Py = Hy / float(x.size) pxy = Pxy.ravel() px = Px.repeat(Py.size) py = pylab.tile(Py, Px.size) idx = pylab.find((pxy > 0) & (px > 0) & (py > 0)) mi = (pxy[idx] * pylab.log2(pxy[idx] / (px[idx] * py[idx]))).sum() return mi
def __gauss(sacobj, Tn, alpha): """ Return envelope and gaussian filtered data """ import pylab as pl data = pl.array(sacobj.data) delta = sacobj.delta Wn = 1 / float(Tn) Nyq = 1 / (2 * delta) old_size = data.size pad_size = 2**(int(pl.log2(old_size)) + 1) data.resize(pad_size) spec = pl.fft(data) spec.resize(pad_size) W = pl.array(pl.linspace(0, Nyq, pad_size)) Hn = spec * pl.exp(-1 * alpha * ((W - Wn) / Wn)**2) Qn = complex(0, 1) * Hn.real - Hn.imag hn = pl.ifft(Hn).real qn = pl.ifft(Qn).real an = pl.sqrt(hn**2 + qn**2) an.resize(old_size) hn = hn[0:old_size] return (an, hn)
def __gauss(sacobj, Tn, alpha): """ Return envelope and gaussian filtered data """ import pylab as pl data = pl.array(sacobj.data) delta = sacobj.delta Wn = 1 / float(Tn) Nyq = 1 / (2 * delta) old_size = data.size pad_size = 2**(int(pl.log2(old_size))+1) data.resize(pad_size) spec = pl.fft(data) spec.resize(pad_size) W = pl.array(pl.linspace(0, Nyq, pad_size)) Hn = spec * pl.exp(-1 * alpha * ((W-Wn)/Wn)**2) Qn = complex(0,1) * Hn.real - Hn.imag hn = pl.ifft(Hn).real qn = pl.ifft(Qn).real an = pl.sqrt(hn**2 + qn**2) an.resize(old_size) hn = hn[0:old_size] return(an, hn)
def __init__(self, X0, X1, pvalue=None, intensity=None): """data should be a time series/numpy array or whatever can be converted to 1D list. The data should be log2 fold change fold change depends on intensity (if you don't have a p-value), as there is more vairability at low intensities, so always keep an eye on the intensity as well as the fold change. Sort them by fold change, but have the average intensity on the side. A fold change of 3 but very low intensity is not very reliable... """ self.fold_change = pylab.log2(X1 / X0) self.pvalue = pvalue if pvalue == None: # assume a normal distribution mean 0 and sigma 1 import scipy.stats self.pvalue = - pylab.log10(scipy.stats.norm.pdf(abs(self.fold_change), 0,1)), self.intensity = intensity if self.intensity is None: self.intensity = intensity
def build_fft(input_signal, filter_coefficients, threshold_windows=6, boundary=0): """generate fast transform fourier by windows Params : input_signal : the audio signal filter_coefficients : coefficients of the chirplet bank threshold_windows : calcul the size of the windows boundary : manage the bounds of the signal Returns : fast Fourier transform applied by windows to the audio signal """ num_coeffs = filter_coefficients.size #print(n,boundary,M) half_size = num_coeffs // 2 signal_size = input_signal.size #power of 2 to apply fast fourier transform windows_size = 2**ceil(log2(num_coeffs * (threshold_windows + 1))) number_of_windows = floor(signal_size // windows_size) if number_of_windows == 0: return fft_based(input_signal, filter_coefficients, boundary) windowed_fft = empty_like(input_signal) #pad with 0 to have a size in a power of 2 windows_size = int(windows_size) zeropadding = np.lib.pad(filter_coefficients, (0, windows_size - num_coeffs), 'constant', constant_values=0) h_fft = fft(zeropadding) #to browse the whole signal current_pos = 0 #apply fft to a part of the signal. This part has a size which is a power #of 2 if boundary == 0: #ZERO PADDING #window is half padded with since it's focused on the first half window = input_signal[current_pos:current_pos + windows_size - half_size] zeropaddedwindow = np.lib.pad(window, (len(h_fft) - len(window), 0), 'constant', constant_values=0) x_fft = fft(zeropaddedwindow) elif boundary == 1: #SYMMETRIC window = concatenate([ flipud(input_signal[:half_size]), input_signal[current_pos:current_pos + windows_size - half_size] ]) x_fft = fft(window) else: x_fft = fft(input_signal[:windows_size]) windowed_fft[:windows_size - num_coeffs] = (ifft( x_fft * h_fft)[num_coeffs - 1:-1]).real current_pos += windows_size - num_coeffs - half_size #apply fast fourier transofm to each windows while current_pos + windows_size - half_size <= signal_size: x_fft = fft(input_signal[current_pos - half_size:current_pos + windows_size - half_size]) #Suppress the warning, work on the real/imagina windowed_fft[current_pos:current_pos + windows_size - num_coeffs] = (ifft(x_fft * h_fft)[num_coeffs - 1:-1]).real current_pos += windows_size - num_coeffs # print(countloop) #apply fast fourier transform to the rest of the signal if windows_size - (signal_size - current_pos + half_size) < half_size: window = input_signal[current_pos - half_size:] zeropaddedwindow = np.lib.pad( window, (0, int(windows_size - (signal_size - current_pos + half_size))), 'constant', constant_values=0) x_fft = fft(zeropaddedwindow) windowed_fft[current_pos:] = roll(ifft( x_fft * h_fft), half_size)[half_size:half_size + windowed_fft.size - current_pos].real windowed_fft[-half_size:] = convolve(input_signal[-num_coeffs:], filter_coefficients, 'same')[-half_size:] else: window = input_signal[current_pos - half_size:] zeropaddedwindow = np.lib.pad( window, (0, int(windows_size - (signal_size - current_pos + half_size))), 'constant', constant_values=0) x_fft = fft(zeropaddedwindow) windowed_fft[current_pos:] = ifft( x_fft * h_fft)[num_coeffs - 1:num_coeffs + windowed_fft.size - current_pos - 1].real return windowed_fft
def __init__(self, image, parent=None, title='', mode='LM', size = (800,700), glCanvas=None): AUIFrame.__init__(self,parent, -1, title,size=size, pos=wx.DefaultPosition) self.mode = mode self.glCanvas = glCanvas self.updateHooks = [] self.statusHooks = [] self.installedModules = [] self.dataChangeHooks = [] self.updating = False if glCanvas: self.glCanvas.wantViewChangeNotification.add(self) self.timer = mytimer() self.timer.Start(10000) self.image = image #self.image = ImageStack(data = dstack, mdh = mdh, filename = filename, queueURI = queueURI, events = None) if not self.image.filename is None and title == '': self.SetTitle(self.image.filename) self.do = DisplayOpts(self.image.data) if self.image.data.shape[1] == 1: self.do.slice = self.do.SLICE_XZ self.do.Optimise() if self.image.mdh and 'ChannelNames' in self.image.mdh.getEntryNames(): chan_names = self.image.mdh.getEntry('ChannelNames') if len(chan_names) == self.image.data.shape[3]: self.do.names = chan_names #self.vp = ArraySettingsAndViewPanel(self, self.image.data, wantUpdates=[self.update], mdh=self.image.mdh) #self.view = ArrayViewPanel(self, do=self.do) #self.AddPage(self.view, True, 'Data') #self._mgr.AddPane(self.vp, aui.AuiPaneInfo(). # Name("Data").Caption("Data").Centre().CloseButton(False).CaptionVisible(False)) self.mainFrame = weakref.ref(self) #self.do = self.vp.do tmp_menu = wx.Menu() tmp_menu.Append(wx.ID_OPEN, '&Open', "", wx.ITEM_NORMAL) tmp_menu.Append(wx.ID_SAVE, "&Save As", "", wx.ITEM_NORMAL) tmp_menu.Append(wx.ID_SAVEAS, "&Export Cropped", "", wx.ITEM_NORMAL) #a submenu for modules to hook and install saving functions into self.save_menu = wx.Menu() self._menus['Save'] = self.save_menu tmp_menu.AppendMenu(-1, 'Save &Results', self.save_menu) tmp_menu.AppendSeparator() tmp_menu.Append(wx.ID_CLOSE, "Close", "", wx.ITEM_NORMAL) self.menubar.Append(tmp_menu, "File") self.view_menu = wx.Menu() self.menubar.Append(self.view_menu, "&View") self._menus['View'] = self.view_menu #'extras' menu for modules to install stuff into self.mProcessing = wx.Menu() self.menubar.Append(self.mProcessing, "&Processing") self._menus['Processing'] = self.mProcessing # Menu Bar end self.Bind(wx.EVT_MENU, self.OnOpen, id=wx.ID_OPEN) self.Bind(wx.EVT_MENU, self.OnSave, id=wx.ID_SAVE) self.Bind(wx.EVT_MENU, self.OnExport, id=wx.ID_SAVEAS) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.statusbar = self.CreateStatusBar(1, wx.STB_SIZEGRIP) self.panesToMinimise = [] modules.loadMode(self.mode, self) self.CreateModuleMenu() self.optionspanel = OptionsPanel(self, self.do, thresholdControls=True) self.optionspanel.SetSize(self.optionspanel.GetBestSize()) pinfo = aui.AuiPaneInfo().Name("optionsPanel").Right().Caption('Display Settings').CloseButton(False).MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False) self._mgr.AddPane(self.optionspanel, pinfo) self.panesToMinimise.append(pinfo) self._mgr.AddPane(self.optionspanel.CreateToolBar(self), aui.AuiPaneInfo().Name("ViewTools").Caption("View Tools").CloseButton(False). ToolbarPane().Right().GripperTop()) if self.do.ds.shape[2] > 1: from PYME.DSView.modules import playback self.playbackpanel = playback.PlayPanel(self, self) self.playbackpanel.SetSize(self.playbackpanel.GetBestSize()) pinfo1 = aui.AuiPaneInfo().Name("playbackPanel").Bottom().Caption('Playback').CloseButton(False).MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False) self._mgr.AddPane(self.playbackpanel, pinfo1) self.do.WantChangeNotification.append(self.playbackpanel.update) #self.mWindows = wx.Menu() #self.menubar.append(self.mWindows, '&Composite With') self.do.WantChangeNotification.append(self.update) self.CreateFoldPanel() for pn in self.panesToMinimise: self._mgr.MinimizePane(pn) #self._mgr.MinimizePane(pinfo2) self.Layout() if 'view' in dir(self): sc = pylab.floor(pylab.log2(1.0*self.view.Size[0]/self.do.ds.shape[0])) #print self.view.Size[0], self.do.ds.shape[0], sc self.do.SetScale(sc) self.view.Refresh() self.update() self.drop = dt() self.SetDropTarget(self.drop) self.AddMenuItem('Save', 'To Cluster', self.OnSaveToCluster) openViewers[self.image.filename] = self
import numpy import pylab x = int(input("please enter a number for x ")) y = int(input("please enter a number for y ")) print(x**y) print(numpy.log2(x)) print(pylab.log2(y))
def lepow2(x): return 2 ** pylab.floor(pylab.log2(x))
def get_entropy_from_isi_array(isi, draw=True, file_name="", quant=None): if quant: T0 = quant else: T0 = 0.9*min(isi) # ISI binarization print("ISI binarization with interval "+str(T0)) out_bin = [] isi_idx = 0 Tcurr = isi[0] while True: if T0 >= Tcurr: out_bin.append(1) isi_idx += 1 if isi_idx >= len(isi): break Tcurr = isi[isi_idx] - (T0 - Tcurr) else: out_bin.append(0) Tcurr -= T0 N = len(out_bin) invN = 1.0/N # Entropy calculation print("Entropy calculation, naive method") MaxOrder = 100 Hvals = list() Hdelt = list() delta = 0.0 del_prev = 0.0 Hprev = 0.0 Intervals = (N-MaxOrder)*[0] for Horder in range(1, MaxOrder+1): xp = list() yp = list() tree = bst.BinarySearchTree() for i, intv in enumerate(Intervals): T = (intv << 1) | out_bin[i+Horder-1] Intervals[i] = T key = T value = tree.get(key) if value: tree.put(key, value+1) else: tree.put(key, 1) H = 0.0 for key, val in tree.root: p = val * invN H -= p * pl.log2(p) xp.append(key) yp.append(val) if Horder == 0: # choose any to view probabilities picture pl.plot(xp, yp, '.-') pl.grid(True) pl.title(file_name) pl.show() return if Horder > 1: delta = (H - Hprev) Hdelt.append(delta) if abs(delta - del_prev) < 1.e-5: break del_prev = delta Hvals.append(H) Hprev = H print("Order " + str(Horder) +" entropy: "+str(H)+", delta: "+str(delta)) if draw: fig = pl.figure() fig.suptitle(file_name+", Bin interval: "+str(T0) + "\nH("+str(Horder)+"): "+str(H)) sp1 = fig.add_subplot(211) sp1.plot([o for o in range(1, len(Hvals)+1)], Hvals) sp1.set_ylabel("Shannon entropy, H(N)") sp1.grid(True) sp2 = fig.add_subplot(212, sharex=sp1) sp2.plot([o for o in range(1, len(Hdelt)+1)], Hdelt) sp2.set_xlabel("Binary word length, N") sp2.set_ylabel("Conditional entropy, H(N) - H(N-1)") sp2.grid(True) pl.draw() pl.show() return delta, H
def get_G_entropy_from_isi_array_nobin(isi, draw=True, file_name="", quant=None, shift=5): """ Entropy estimator from Grassberger-2008 """ if quant: T0 = None Tqua = quant else: T0 = 0.9*min(isi) Tqua = T0 / 10.0 # Entropy calculation print("Entropy calculation, Grassberger method, no binarization") print("min(isi): " + str(T0) + ", quantization Tqua: " + str(Tqua)) MaxOrder = 100 Shift = shift Hvals = list() Hdelt = list() delta = 0.0 del_prev = 0.0 Hprev = 0.0 ISI_len = len(isi) G = update_G_until([], 2) max_of_max_n = 2 for Horder in range(1, MaxOrder+1): tree = bst.BinarySearchTree() N = 0 i = 0 while i+Horder < ISI_len: T = 0.0 for j in range(Horder): T = T + isi[i + j] key = round(T/Tqua) value = tree.get(key) if value: tree.put(key, value+1) else: tree.put(key, 1) N += 1 i += min(Horder, Shift) H = 0.0 n_vals = [] for key, val in tree.root: n_vals.append(val) # Update G[] array, if necessary max_n = max(n_vals) if max_n > max_of_max_n: max_of_max_n = max_n G = update_G_until(G, max_n) for val in n_vals: H -= val * G[val] H /= N H += pl.log(N) H = H * pl.log2(pl.e) # to log2 format if Horder > 1: delta = (H - Hprev) Hdelt.append(delta) if abs(delta - del_prev) < 1.e-5: break del_prev = delta Hvals.append(H) Hprev = H print("Order " + str(Horder) +" entropy: "+str(H)+", delta: "+str(delta)) if draw: fig = pl.figure() fig.suptitle(file_name+", Bin interval: "+str(T0) + "\nH("+str(Horder)+"): "+str(H)) sp1 = fig.add_subplot(211) sp1.plot([o for o in range(1, len(Hvals)+1)], Hvals) sp1.set_ylabel("Shannon entropy, H(N)") sp1.grid(True) sp2 = fig.add_subplot(212, sharex=sp1) sp2.plot([o for o in range(1, len(Hdelt)+1)], Hdelt) sp2.set_xlabel("Binary word length, N") sp2.set_ylabel("Conditional entropy, H(N) - H(N-1)") sp2.grid(True) pl.draw() pl.show() return delta, H
def get_G_entropy_from_isi_array(isi, draw=True, file_name="", quant=None, shift=5): """ Entropy estimator from Grassberger-2008 """ if quant: T0 = quant else: T0 = 0.9*min(isi) # ISI binarization print("ISI binarization") out_bin = [] isi_idx = 0 Tcurr = isi[0] while True: if T0 >= Tcurr: out_bin.append(1) isi_idx += 1 if isi_idx >= len(isi): break Tcurr = isi[isi_idx] - (T0 - Tcurr) else: out_bin.append(0) Tcurr -= T0 #if len(out_bin) < 50: #print(out_bin[len(out_bin)-1]) print("Digit count: "+str(len(out_bin))) # Entropy calculation print("Entropy calculation, Grassberger method") MaxOrder = 100 Shift = shift Hvals = list() Hdelt = list() delta = 0.0 del_prev = 0.0 Hprev = 0.0 out_bin_len = len(out_bin) G = update_G_until([], 2) max_of_max_n = 2 for Horder in range(1, MaxOrder+1): tree = bst.BinarySearchTree() N = 0 i = 0 while i+Horder < out_bin_len: T = 0 for j in range(Horder): T = (T << 1) | out_bin[i + j] key = T value = tree.get(key) if value: tree.put(key, value+1) else: tree.put(key, 1) N += 1 i += min(Horder, Shift) H = 0.0 n_vals = [] for key, val in tree.root: n_vals.append(val) # Update G[] array, if necessary max_n = max(n_vals) if max_n > max_of_max_n: max_of_max_n = max_n G = update_G_until(G, max_n) for val in n_vals: H -= val * G[val] H /= N H += pl.log(N) H = H * pl.log2(pl.e) # to log2 format if Horder > 1: delta = (H - Hprev) Hdelt.append(delta) if abs(delta - del_prev) < 1.e-5: break del_prev = delta Hvals.append(H) Hprev = H print("Order " + str(Horder) +" entropy: "+str(H)+", delta: "+str(delta)+ ", N: " + str(N)) if draw: fig = pl.figure() fig.suptitle(file_name+", Bin interval: "+str(T0) + "\nH("+str(Horder)+"): "+str(H)) sp1 = fig.add_subplot(211) sp1.plot([o for o in range(1, len(Hvals)+1)], Hvals) sp1.set_ylabel("Shannon entropy, H(N)") sp1.grid(True) sp2 = fig.add_subplot(212, sharex=sp1) sp2.plot([o for o in range(1, len(Hdelt)+1)], Hdelt) sp2.set_xlabel("Binary word length, N") sp2.set_ylabel("Conditional entropy, H(N) - H(N-1)") sp2.grid(True) pl.draw() pl.show() return delta, H
r, g, b = scaler, 0, 1 else: r, g, b = 1, 0, 1 - scaler return r, g, b jack.attach("colours") jack.register_port("in", jack.IsInput) jack.activate() jack.connect("system:capture_1", "colours:in") buff = jack.get_buffer_size() rate = jack.get_sample_rate() freqs = np.fft.fftfreq(buff, 1.0 / rate)[: buff / 2] hues = array([(log2(F) - log2(440)) % 1 for F in freqs]) hue_order = array(sorted(enumerate(hues[1:], 1), key=lambda f: f[1]), "i").T[0] freq_rgb = array([hue_to_rgb(h) for h in hues]) capture = np.zeros((1, buff), "f") dummy = np.zeros((0, 0), "f") pygame.init() size = (1024, 32) window = pygame.display.set_mode(size) ffact = size[0] / float(len(freqs)) while True: try: jack.process(dummy, capture)
def entropy(words): N = float(len(words)) P = [words.count(w)/N for w in set(words)] return -sum([p*log2(p) for p in P])
def numAdd(init, nex): if init < 2: return float('inf'), init add = max(int(ceil(log2(float(nex) / (init - 1)))), 0) size = 2**add * (init - 1) + 1 + nex return add, size
def _12TET(fs): return 12 * pl.log2(fs / 27.5)
# -*- coding: utf-8 -*- """ Created on Tue Jun 23 18:20:20 2020 @author: Sharon G """ # Problem Set 0 # Write a program that does the following in order: # 1. Asks the user to enter a number “x” # 2. Asks the user to enter a number “y” # 3. Prints out number “x”, raised to the power “y”. # 4. Prints out the log (base 2) of “x”. # Please note that the assignment requests the use of numpy or pylab. # For this reason, multiple methods have been included for executing # the requested commands. x = int(input("Hello User, and Welcome to PS_0\nPlease enter a value for variable x:")) y = int(input("Next, please enter a value for variable y:")) import math print("Importing math:") print("The value of x, raised to the power of y, is", x**y, ".") print("The log (base 2) of x is", math.log(x, 2), ".") import numpy print("Importing numpy:") print("The log (base 2) of x, is", numpy.log2(x), ".") import pylab print("Importing pylab:") print("The log (base 2) of x, is", pylab.log2(x), ".")
from pylab import log2 x = int(input('Enter number x: ')) y = int(input('Enter number y: ')) print('x ** y = {}'.format(x**y)) print(log2(x))
def __init__(self, image, parent=None, title='', mode='LM', size = (800,700), glCanvas=None): wx.Frame.__init__(self,parent, -1, title,size=size, pos=(1100, 300)) self.SetAutoLayout(True) self.mode = mode self.glCanvas = glCanvas self.paneHooks = [] self.updateHooks = [] self.statusHooks = [] self.installedModules = [] self.dataChangeHooks = [] self.updating = False if glCanvas: self.glCanvas.wantViewChangeNotification.add(self) self.pane0 = None self.timer = mytimer() self.timer.Start(10000) self.image = image #self.image = ImageStack(data = dstack, mdh = mdh, filename = filename, queueURI = queueURI, events = None) if not self.image.filename == None and title == '': self.SetTitle(self.image.filename) self._mgr = aui.AuiManager(agwFlags = aui.AUI_MGR_DEFAULT | aui.AUI_MGR_AUTONB_NO_CAPTION) atabstyle = self._mgr.GetAutoNotebookStyle() self._mgr.SetAutoNotebookStyle((atabstyle ^ aui.AUI_NB_BOTTOM) | aui.AUI_NB_TOP) # tell AuiManager to manage this frame self._mgr.SetManagedWindow(self) self.do = DisplayOpts(self.image.data) if self.image.data.shape[1] == 1: self.do.slice = self.do.SLICE_XZ self.do.Optimise() if self.image.mdh and 'ChannelNames' in self.image.mdh.getEntryNames(): self.do.names = self.image.mdh.getEntry('ChannelNames') #self.vp = ArraySettingsAndViewPanel(self, self.image.data, wantUpdates=[self.update], mdh=self.image.mdh) #self.view = ArrayViewPanel(self, do=self.do) #self.AddPage(self.view, True, 'Data') #self._mgr.AddPane(self.vp, aui.AuiPaneInfo(). # Name("Data").Caption("Data").Centre().CloseButton(False).CaptionVisible(False)) self.mainFrame = weakref.ref(self) #self.do = self.vp.do self._menus = {} # Menu Bar self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) tmp_menu = wx.Menu() tmp_menu.Append(wx.ID_OPEN, '&Open', "", wx.ITEM_NORMAL) tmp_menu.Append(wx.ID_SAVE, "&Save As", "", wx.ITEM_NORMAL) tmp_menu.Append(wx.ID_SAVEAS, "&Export Cropped", "", wx.ITEM_NORMAL) #a submenu for modules to hook and install saving functions into self.save_menu = wx.Menu() self._menus['Save'] = self.save_menu tmp_menu.AppendMenu(-1, 'Save &Results', self.save_menu) tmp_menu.AppendSeparator() tmp_menu.Append(wx.ID_CLOSE, "Close", "", wx.ITEM_NORMAL) self.menubar.Append(tmp_menu, "File") self.view_menu = wx.Menu() self.menubar.Append(self.view_menu, "&View") self._menus['View'] = self.view_menu #'extras' menu for modules to install stuff into self.mProcessing = wx.Menu() self.menubar.Append(self.mProcessing, "&Processing") self._menus['Processing'] = self.mProcessing # Menu Bar end wx.EVT_MENU(self, wx.ID_OPEN, self.OnOpen) wx.EVT_MENU(self, wx.ID_SAVE, self.OnSave) wx.EVT_MENU(self, wx.ID_SAVEAS, self.OnExport) wx.EVT_CLOSE(self, self.OnCloseWindow) wx.EVT_SIZE(self, self.OnSize) self.statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP) self.panesToMinimise = [] modules.loadMode(self.mode, self) self.CreateModuleMenu() self.optionspanel = OptionsPanel(self, self.do, thresholdControls=True) self.optionspanel.SetSize(self.optionspanel.GetBestSize()) pinfo = aui.AuiPaneInfo().Name("optionsPanel").Right().Caption('Display Settings').CloseButton(False).MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False) self._mgr.AddPane(self.optionspanel, pinfo) self.panesToMinimise.append(pinfo) self._mgr.AddPane(self.optionspanel.CreateToolBar(self), aui.AuiPaneInfo().Name("ViewTools").Caption("View Tools").CloseButton(False). ToolbarPane().Right().GripperTop()) if self.do.ds.shape[2] > 1: from PYME.DSView.modules import playback self.playbackpanel = playback.PlayPanel(self, self) self.playbackpanel.SetSize(self.playbackpanel.GetBestSize()) pinfo1 = aui.AuiPaneInfo().Name("playbackPanel").Bottom().Caption('Playback').CloseButton(False).MinimizeButton(True).MinimizeMode(aui.AUI_MINIMIZE_CAPT_SMART|aui.AUI_MINIMIZE_POS_RIGHT)#.CaptionVisible(False) self._mgr.AddPane(self.playbackpanel, pinfo1) self.do.WantChangeNotification.append(self.playbackpanel.update) #self.mWindows = wx.Menu() #self.menubar.append(self.mWindows, '&Composite With') self.do.WantChangeNotification.append(self.update) self.CreateFoldPanel() self._mgr.Update() for pn in self.panesToMinimise: self._mgr.MinimizePane(pn) #self._mgr.MinimizePane(pinfo2) self.Layout() if 'view' in dir(self): sc = pylab.floor(pylab.log2(1.0*self.view.Size[0]/self.do.ds.shape[0])) #print self.view.Size[0], self.do.ds.shape[0], sc self.do.SetScale(sc) self.view.Refresh() self.update() self.drop = dt() self.SetDropTarget(self.drop) openViewers[self.image.filename] = self