def run(self): while True: self.board_to_compare = getRepresentation(self.boundaries, get_frame()) plot_array(self.board_to_compare) move = self.get_move() name = raw_input('Press enter to continue') self.prev_board = self.board_to_compare
def get_move(self, plot=False): move = False self.board_to_compare = getRepresentation(get_frame(), self.boundaries) move = self.compare_boards() while not move: print 'An error occured, please adjust pieces in the following places: {}'.format(self.diffs) if plot: plot_array(self.board_to_compare) #raw_input('Press any key to check again') self.board_to_compare = getRepresentation(get_frame(), self.boundaries) move = self.compare_boards() self.prev_board = self.board_to_compare if plot: plot_array(self.board_to_compare) return move
def __init__(self, plot=False): self.diffs = [] self.boundaries = calibrate() raw_input('Calibration is complete, please put chesspieces to their positions, then press any key') initialBoard = createInitialBoardMatrix() frame = get_frame() currentBoard = getRepresentation(frame, self.boundaries) while not np.array_equal(initialBoard, currentBoard): print 'Could not detect correct setup, try again' if plot: plot_array(currentBoard) currentBoard = getRepresentation(get_frame(), self.boundaries) print currentBoard time.sleep(1) self.prev_board = currentBoard self.board_to_compare = None
sf = 1.05 xmin = sf * np.min(Y[:, 0]) xmax = sf * np.max(Y[:, 0]) ymin = sf * np.min(Y[:, 1]) ymax = sf * np.max(Y[:, 1]) dx = float(xmax - xmin) / npts dy = float(ymax - ymin) / npts xx, yy = np.mgrid[xmin:xmax:dx, ymin:ymax:dy] positions = np.vstack([xx.ravel(), yy.ravel()]) #kernel = st.gaussian_kde(Y.T, bw_method = 'silverman'); kernel = st.gaussian_kde(Y.T, bw_method=0.25) Y_xy = kernel(positions) Y_xy = np.reshape(Y_xy, xx.shape) fplt.plot_array(Y_xy) #watershed it from scipy import ndimage as ndi from skimage.morphology import watershed from skimage.feature import peak_local_max local_maxi = peak_local_max(Y_xy, indices=False, footprint=np.ones((7, 7))) markers = ndi.label(local_maxi)[0] labels = watershed(-Y_xy, markers) #, mask=image) #classify points Y_idx = np.array(np.round( (Y - [xmin, ymin]) / [xmax - xmin, ymax - ymin] * (npts - 1)), dtype=int)
memmap='r+') fres_tn[:, i, :] = exp.bin_data(fres[:, i, :], sbins) pool = Pool(processes=12) pool.map(norm, range(fres.shape[1])) # plot res_tn = exp.load('%s_%s_time_normalized_scales_mean.npy' % (strain, feat), memmap='r') dorder = exp.load('%s_%s_order.npy' % (strain, feat)) datplt = alys.scales_to_array(res_tn, worms_first=False, order=dorder) fig = fplt.plot_array(datplt, title='%s %s time normalized scales mean' % (strain, feat)) fplt.savefig(fig, exp.figname('%s_%s_time_normalized_scales_mean.png' % (strain, feat)), width=2500) datplt = alys.scales_to_array(res_tn, worms_first=True, order=dorder) fig = fplt.plot_array(datplt, title='%s %s time normalized scales mean' % (strain, feat)) fplt.savefig(fig, exp.figname('%s_%s_time_normalized_scales_mean_2.png' % (strain, feat)), width=2500)
cwt[:, data.stage_switch[i] + k] = vmax plt.imshow( cwt, aspect='auto', cmap='PRGn', # interpolation = 'none', vmin=vmin, vmax=vmax) plt.tight_layout() import plot as fplt import experiment as exp wd = exp.scales_to_array(fwt, worms_first=False) fplt.plot_array(wd) s = [11, 12, 13, 14, 15, 16] plt.figure(10) plt.clf() nplt = len(s) for i, s in enumerate(s): plt.subplot(nplt, 1, i + 1) cwt = fwt[:, s, :].copy() #for k in range(-200,200,1): # cwt[:,data.stage_switch[i] + k] = vmax; vmin = cwt.min() vmax = cwt.max() vmin = max(vmin, -vmax) vmax = min(vmax, -vmin) red = 0.5
nscales = dat_scales.shape[1]; ntimes = dat_scales.shape[2]; dist_scales = np.zeros((nscales, dbins, ntimes)); dat_max_scales = np.zeros(nscales); dat_min_scales = np.zeros(nscales); for s in range(nscales): dat_max_scales[s] = np.percentile(dat_scales[:,s,:], 100); dat_min_scales[s] = np.percentile(dat_scales[:,s,:], 5); for t in range(ntimes): dist_scales[s,:,t] = np.histogram(dat_scales[:,s,t], range = (dat_min_scales[s],dat_max_scales[s]), bins = dbins)[0]; dist_scales[s,:,t] /= dist_scales[s,:,t].sum(); dp = np.zeros((nscales*dbins, ntimes)); for i in range(nscales): dp[(i*dbins):((i+1)*dbins),:] = dist_scales[i,:,:]; cutoff = 0.2; dp[dp > cutoff] = cutoff; fplt.plot_array(dp) plt.figure(10); plt.clf(); plt.plot(dat_max_scales,'b'); plt.plot(dat_min_scales,'r'); #plt.figure(11); plt.clf(); #fplt.plot_image_array(dist_scales[:5], names = [str(i) for i in range(5)])
except: pass median_val = np.median(l) return True, median_val if i != 1 or 2: return False, None def openAndInitializeImage(filename): image = cv2.imread(filename, 1) #image = cv2.GaussianBlur(image, (7,7),0) #image = cv2.medianBlur(image, 7) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) return image if __name__ == '__main__': #Usage: python <calibrationimage> <image_to_be_checked> calibration_image_filename = sys.argv[1] chessboard_image_filename = sys.argv[2] calibration_image = openAndInitializeImage(calibration_image_filename) chessboard_image = openAndInitializeImage(chessboard_image_filename) boundaries = calibrate(calibration_image) res = getRepresentation(chessboard_image, boundaries) try: from plot import plot_array plot_array(res) except: print res
import plot as fplt strain = 'N2' feat = 'roam' nbins = 2**13 save_fig = True data = exp.load_data(strain) ### Bin data sbins = exp.stage_bins(data, nbins=nbins) d = getattr(data, feat) tn = exp.bin_data(d, sbins) exp.save(tn, '%s_%s_time_normalized.npy' % (strain, feat)) #fig = plt.figure(1); plt.clf(); #plt.imshow(tn, aspect = 'auto'); #plt.tight_layout(); #plt.title('%s %s time normalized' % (strain, feat)); #if save_fig: # fig.savefig(exp.figname('%s_%s_time_normalized.png'% (strain, feat))); fig = fplt.plot_array(tn, title='%s %s time normalized' % (strain, feat)) fplt.savefig(fig, exp.figname('%s_%s_time_normalized.png' % (strain, feat)), width=2500)
xy_switch = (xy_stage_ids[rd_to_xy[valid]].T - xy_stage_ids[rd_to_xy[valid]][:, 1] + rd_switch[:, 1]).T ww = 500 for wid in range(nworms): for s in range(1, 6): rd[wid, max(rd_switch[wid, s] - ww, 0):min(rd_switch[wid, s] + ww, rd.shape[1])] = 3 rd[wid, max(xy_switch[wid, s] - ww, 0):min(xy_switch[wid, s] + ww, rd.shape[1])] = 4 import plot as fplt #import analysis.plot as fplt; fplt.plot_array(rd) #plt.figure(10); plt.clf(); #plt.imshow(rd, aspect = 'auto', cmap = plt.cm.viridis) rate = 3.0 * 60 * 60 valid = rd_to_xy >= 0 xy_switch_hr = np.round(xy_switch / rate) rd_switch_hr = np.round(rd_switch / rate) #xy_switch_hr = xy_switch / rate #rd_switch_hr = rd_switch / rate fig = plt.figure(2) plt.clf() plt.plot(xy_switch_hr[:, :-1], rd_switch_hr[:, :-1], '*')
model = hmm(nstates=2) model.fit([d[wid]]) model.fit(d, n_jobs=12) pred = 1 - np.array(model.predict(d[wid])) plt.figure(3) plt.clf() ax = plt.subplot(2, 1, 1) plt.plot(d[wid]) plt.ylim(0, 1.5) plt.title('data') plt.subplot(2, 1, 2, sharex=ax) plt.plot(pred) plt.ylim(0, 1.5) plt.title('pred') import plot as fplt fplt.plot_array(np.vstack([d[wid], pred, d[wid] - pred])) np.abs(d[wid] - pred).sum() ### isi distribution of this import analysis as als disi = als.isi_onoff(d)
cwt = fwt[i].copy(); for k in range(-200,200,1): cwt[:,data.stage_switch[i] + k] = vmax; plt.imshow(cwt,aspect='auto', cmap='PRGn',# interpolation = 'none', vmin=vmin, vmax=vmax); plt.tight_layout(); import plot as fplt import experiment as exp wd = exp.scales_to_array(fwt, worms_first=False); fplt.plot_array(wd) s = [11,12,13,14,15,16]; plt.figure(10); plt.clf(); nplt = len(s); for i,s in enumerate(s): plt.subplot(nplt,1,i+1); cwt = fwt[:,s,:].copy(); #for k in range(-200,200,1): # cwt[:,data.stage_switch[i] + k] = vmax; vmin = cwt.min(); vmax = cwt.max(); vmin = max(vmin,-vmax); vmax = min(vmax, -vmin); red = 0.5; vmin *= red; vmax *= red; plt.imshow(cwt,aspect='auto', cmap='PRGn', # interpolation = 'none',
ed = sbins[1][wid] for i, se in enumerate(zip(st, ed)): s, e = se pp, cc = pk.maximum_likelihood_probabilities(d[wid, s:e]) c[wid, i] = [cc[(0, 1)], cc[(1, 0)]] p[wid, i] = [pp[0], pp[1]] ### plot the result import matplotlib.pyplot as plt plt.figure(1) plt.clf() wid = 0 plt.subplot(2, 1, 1) plt.plot(c[wid, :, 0]) plt.plot(c[wid, :, 1]) plt.subplot(2, 1, 2) plt.plot(p[wid, :, 0]) plt.plot(p[wid, :, 1]) import plot as fplt fplt.plot_array(p[:, :, 1], title='%s %s probability' % (strain, feat)) #fplt.plot_array(p[:,:,1]) cc = c.copy() cc[cc > 0.5] = 0.5 fplt.plot_array(cc[:, :, 0], title='%s %s 0->1' % (strain, feat)) fplt.plot_array(cc[:, :, 1], title='%s %s 1->0' % (strain, feat))
nfmax = 50 plt.pcolormesh(t, f[:nfmax], Sxx[:nfmax, :]) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.tile('spectogram %s %s %d' % (strain, fn, iworm)) plt.subplot(2, 1, 2, sharex=ax) tt = np.linspace(0, t[-1], ntimes) plt.plot(tt, d[iworm, :ntimes]) plt.figure(3 * fi) plt.clf() ax = plt.subplot(2, 1, 1) smax = 0.05 nfmax = -1 sxx2 = Sxx.copy() sxx2[sxx2 > smax] = smax plt.pcolormesh(t, f[:nfmax], sxx2[:nfmax, :]) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.show() plt.subplot(2, 1, 2, sharex=ax) tt = np.linspace(0, t[-1], ntimes) plt.plot(tt, d[iworm, :ntimes]) fplt.plot_array(sxx2, title='spectorgram %s %s %d' % (strain, fn, iworm)) plt.figure(4 * fi) plt.clf() plt.plot(np.sum(sxx2, axis=0)) plt.title('sum spectorgram %s %s %d' % (strain, fn, iworm))