this_color = iplot.subspectrum(analyze_hsls+1)[i] if i > 0: g_col_li = [('k',zip(*list(enumerate(Util.smooth(grounds[0],10)))))] else: g_col_li = [] g_col_li.append((this_color,zip(*list(enumerate(Util.smooth(grounds[-1],10)))))) last_frames_objs_ols = vidtools.ols_in_interval(frames_offset-hsl-1,frames_offset,min_arc_score,ols,ols_offset, \ Util.merge_dictlist([objs,to_retire_objs]), \ Util.merge_dictlist([objs_sizes,to_retire_objs_sizes]), \ Util.merge_dictlist([objs_fols,to_retire_objs_fols]), \ size_h, size_bins, fol_h, fol_bins,True) for vfi,m in enumerate(last_frames): if opts.antfarm_config: cv_im = vidtools.mat_polys2cv(m,zip(iplot.subspectrum(6)[1:],list(reversed(last_frames_objs_ols[vfi][:5])))+zip(['k']*len(prevol),prevol),zip([this_color]*len(digol),['\\']*len(digol),digol),g_col_li,80,2) else: cv_im = vidtools.mat_polys2cv(m,zip(iplot.subspectrum(6)[1:],list(reversed(last_frames_objs_ols[vfi][:5]))),[],[],80,2) nll = cv.WriteFrame(vidwriter,cv_im) print >> sys.stderr, '\r\twrite video frame %s' % vfi, retire_objs(ols_offset-hsl,to_retire_objs,to_retire_objs_sizes,to_retire_objs_fols,retired_objs,retired_objs_sizes,retired_objs_fols) i+=1 this_time = int(time.time() - t) times.append(this_time) avg_time = int(numpy.mean(times)) print >> sys.stderr, i, '/', analyze_hsls, 'done in',str(datetime.timedelta(seconds=this_time)),'avg loop time',str(datetime.timedelta(seconds=avg_time)),'done in',str(datetime.timedelta(seconds=avg_time*(analyze_hsls-i))) if i > 5 and avg_time > opts.max_itertime: errstr = 'mean iteration time %s after %s rounds exceeds max %s' % (avg_time,i+1,opts.max_itertime) raise ValueError, errstr
def draw_rainbowtron_opencv(analysis_dir,fig=1,outformat='pdf',vid_fps=30,graph_height=0.2, \ bkgd_data='fullmice',spectrum_len=None,dawn_min=None,activity_percentile_plot=0.5, \ hill_bounds=None,skip_first=0,hsl_per_min=2,set_hill_max=None,set_dig_max=None, \ post_summarize_analysis=True,outfile_prefix=None, \ ground_step_coeff=1,max_pix_mult=None,max_obj=None,max_dist_mult=None,hill_win_coeff=None,write_yval=False, \ hill_max_cumul_digscale=None,dig_max_cumul_digscale=None): '''given a summarize_segment_opencv.py analysis directory (i.e. tarballs of analysis results by half-segment-length) generates a figure showing burrowing activity and sand-hill accumulation if outformat is not None, save figure to analysis_dir if vidformat is not None, record rainbowtron over time to analysis_dir bkgd_data: data to display as background for image. one of ["fullmice","flatmice","hillchange"] if post_summarize_analysis is True, look for ground and activity from vidtools.find_ground_over_frames_matrix; vidtools.find_burrow_over_frames_matrix HACK: if bkgd_data is NOT "fullmice", the mouse size vector will not be loaded, and a mouse_radius of 10 will be used ''' if outfile_prefix is None: outfile_prefix = analysis_dir.rstrip('/').split('/')[-4].split('-')[0] + '-' + ('_'.join(analysis_dir.rstrip('/').split('/')[-3].split('_')[-2:])) outfile_prefix = '%s-hillmax%s-digmax%s-gsc%s-mpm%s-mo%s-mdm%s-hwc%s-hmcd%s-dmcd%s-bkgd_%s' % \ (outfile_prefix, set_hill_max,set_dig_max, \ ground_step_coeff,max_pix_mult,max_obj,max_dist_mult,hill_win_coeff,hill_max_cumul_digscale,dig_max_cumul_digscale, \ bkgd_data) #will get overwritten later if possible mouse_radius = 10 print >> sys.stderr, 'load:' SHAPE = eval(open(analysis_dir+'/SHAPE').read()) config = eval(open(os.path.split(os.path.split(analysis_dir.rstrip('/'))[0])[0]+'-config.dict').read()) if hill_bounds is None: hill_left = 0 hill_right = SHAPE[1] elif hill_bounds == 'config': hill_left,hill_right = config['hill_bounds'] else: hill_left,hill_right = hill_bounds print >> sys.stderr, '\ttar handles' tars_d = dict([(os.path.basename(f),tarfile.open(f)) for f in glob(os.path.join(analysis_dir,'*.tar'))]) print >> sys.stderr, '\tframes' frames = Util.tar2ar_all(tars_d['segavgs.tar'],SHAPE) if bkgd_data == 'hillchange': bkgd_mat = frames[-1]-(frames[0]-frames[-1]) else: if bkgd_data == 'flatmice': print >> sys.stderr, '\tmouse masks' mouse_hists = Util.tar2ar_all(tars_d['mousemasks.tar'],SHAPE,bool) elif bkgd_data == 'fullmice': print >> sys.stderr, '\tmouse locations' hist2d_tarf = os.path.join(analysis_dir,'mousehists-mpm%s-mo%s-mdm%s.tar' % (max_pix_mult,max_obj,max_dist_mult) ) outlines_tarf = os.path.join(analysis_dir,'miceols.tar') # this will save tons of time...eventually... mouse_hists,svec = load_cached_mouse_hist2d_segments(hist2d_tarf,outlines_tarf,SHAPE,check_lengths=True,return_sizes=True, \ max_pix_mult=max_pix_mult,max_obj=max_obj,max_dist_mult=max_dist_mult) #mouse_hists = load_mouse_hist2d_segments(tars_d['miceols.tar'],SHAPE) mouse_radius = math.sqrt(numpy.mean(svec)/math.pi) else: errstr = 'bkgd_data must be one of ["hillchange","flatmice","fullmice"]; got %s' % bkgd_data raise ValueError, errstr bkgd_mat = numpy.log1p(reduce(lambda x,y:x+numpy.array(y,dtype=int), mouse_hists)) print >> sys.stderr, '\tgrounds' if post_summarize_analysis: grounds_postsummary_tarbase = 'grounds_postsummary-gsc%s.tar' % (ground_step_coeff) if grounds_postsummary_tarbase in tars_d: grounds = Util.tar2obj_all(tars_d[grounds_postsummary_tarbase],lambda t:numpy.array(eval(t),dtype=float)) print >> sys.stderr, 'loaded %s grounds' % len(grounds) else: grounds_postsummary_tarf = os.path.join(analysis_dir,grounds_postsummary_tarbase) grounds = vidtools.find_ground_over_frames_matrix(frames,config['ground_anchors'],config['end_ground_anchors'],max_step_limit=mouse_radius*ground_step_coeff) #write grounds so future runs can load cached tarh = tarfile.open(grounds_postsummary_tarf,'w') for g,n in zip(grounds,sorted(tars_d['grounds.tar'].getnames())): Util.obj2tar(g,n,tarh) tarh.close() grounds = map(numpy.array,grounds) else: grounds = [Util.smooth(g,10) for g in Util.tar2obj_all(tars_d['grounds.tar'],lambda t:numpy.array(eval(t),dtype=float))] print >> sys.stderr, '\tactouts' if post_summarize_analysis: newact_ols_postsummary_tarbase = 'newact_ols_postsummary-gsc%s-mpm%s-mo%s-mdm%s.tar' % \ (ground_step_coeff,max_pix_mult,max_obj,max_dist_mult) pd_ols_postsummary_tarbase = 'pd_ols_postsummary-gsc%s-mpm%s-mo%s-mdm%s.tar' % \ (ground_step_coeff,max_pix_mult,max_obj,max_dist_mult) newact_ols_postsummary_tarf = os.path.join(analysis_dir,newact_ols_postsummary_tarbase) pd_ols_postsummary_tarf = os.path.join(analysis_dir,pd_ols_postsummary_tarbase) if newact_ols_postsummary_tarbase in tars_d and pd_ols_postsummary_tarbase in tars_d: actouts = Util.tar2obj_all(tars_d[newact_ols_postsummary_tarbase]) pdols = Util.tar2obj_all(tars_d[pd_ols_postsummary_tarbase]) print >> sys.stderr, 'loaded %s activity outlines' % len(actouts) print >> sys.stderr, 'loaded %s predug outlines' % len(pdols) else: if bkgd_data == 'hillchange': mousemasks = Util.tar2ar_all(tars_d['mousemasks.tar'],SHAPE,bool) else: mousemasks = [numpy.array(m,dtype=bool) for m in mouse_hists] pdmask,pdols,prevactols,actouts = vidtools.find_burrow_over_frames_matrix(frames,mousemasks,grounds,mouse_radius,predug_poly=config.get('predug',None)) na_tarh = tarfile.open(newact_ols_postsummary_tarf,'w') pd_tarh = tarfile.open(pd_ols_postsummary_tarf,'w') for na,pd,n in zip(actouts,pdols,sorted(tars_d['newact_ols.tar'].getnames())): Util.obj2tar(na,n,na_tarh) Util.obj2tar(pd,n,pd_tarh) na_tarh.close() pd_tarh.close() else: actouts = Util.tar2obj_all(tars_d['newact_ols.tar']) if hill_win_coeff is None: hill_area = numpy.array([sum(SHAPE[0]-g[hill_left:hill_right]) for g in grounds]) hill_increase = [] for v in hill_area[1:] - hill_area[:-1]: if 0 < v: hill_increase.append(v) else: hill_increase.append(0) else: #ADD HILL AREA WINDOW CALC win = mouse_radius * hill_win_coeff hill_increase = [] for i,g in enumerate(grounds[1:]): diff_vec = grounds[i] - g hi,win_start = max([(sum(diff_vec[x:x+win]),x) for x in range(len(diff_vec))]) hill_increase.append(hi) hill_increase = numpy.array(hill_increase) grounds = grounds[1:] #drop first ground after calculating differences # takes second (1-th) actout since first is always blank areas = [sum([len(filter(None,vidtools.mask_from_outline(p,frames[0].shape).flat)) for p in polys]) for polys in actouts[1:]] #progs = [True and sum([vidtools.hypotenuse(*t) for t in terms]) or 0 for terms in actterms] #write hill increase and dig areas areas_out = os.path.join(analysis_dir,outfile_prefix+'-dig_areas.list') hills_out = os.path.join(analysis_dir,outfile_prefix+'-hill_increases.list') open(areas_out,'w').write(list(areas).__repr__()) open(hills_out,'w').write(list(hill_increase).__repr__()) #PLOT if hill_max_cumul_digscale: hill_scale_factor = sum(hill_increase)/float(hill_max_cumul_digscale) else: hill_scale_factor = 1 if dig_max_cumul_digscale: dig_scale_factor = sum(areas)/float(dig_max_cumul_digscale) else: dig_scale_factor = 1 if spectrum_len is None: spectrum_len = len(actouts) spec = iplot.subspectrum(spectrum_len,reversed=True,noUV=True) figobj = pylab.figure(fig,figsize=(9,6)) figobj.clf() print >> sys.stderr, 'render:' pylab.gray() if graph_height is not None: h = frames[0].shape[0] * graph_height bkgd_mat = numpy.array(list(bkgd_mat) + list(numpy.zeros((h,bkgd_mat.shape[1])))) pylab.matshow(bkgd_mat,fignum=fig) ax = figobj.axes[0] ax.set_xticks([]) ax.set_yticks([]) for i,poly in enumerate(actouts): for p in poly: if p: ax.add_patch(pylab.matplotlib.patches.Polygon(p,fc='none',ec=spec[i])) if post_summarize_analysis and len(config.get('predug',[])) > 0: for i,poly in enumerate(pdols): for p in poly: if p: ax.add_patch(matplotlib.patches.Polygon(p,ec='gray',fc='none',hatch='/')) vinf,ainf = analysis_dir.split('/analysis/') ax.text(10,20,vinf,fontsize=8,color='w') ax.text(10,35,ainf,fontsize=8,color='w') if graph_height is not None: z3 = (3*hill_increase.std()) + hill_increase.mean() #willing to accept that a mouse kicks out at no more than 2x max observed burrow-build? max_increase = max(2*max(areas),z3) print >> sys.stderr, 'for max ground change, z3 = %s; 2*max_areas = %s. Choose %s' % (z3,2*max(areas),max_increase) for i,v in enumerate(hill_increase): if v > max_increase: hill_increase[i] = 0 h = frames[0].shape[0] * graph_height base = frames[0].shape[0] + h/2 - 10 scale = frames[0].shape[1]/float(len(areas)) x = numpy.arange(0,frames[0].shape[1],scale)[:len(areas)] print len(x),len(hill_increase) if dawn_min: pylab.bar(x[dawn_min],1*h/2,color='w',edgecolor='w',bottom=base) pylab.bar(x[dawn_min],-1*h/2,color='w',edgecolor='w',bottom=base) hours = [] for m in range(min(len(spec),len(areas))): if m%(60*hsl_per_min)==0: hours.append(1) else: hours.append(0) print len(hours) pylab.bar(x,numpy.array(hours)*h/2,color='w',edgecolor='w',alpha=0.4,linewidth=0,bottom=base) pylab.bar(x,-1*numpy.array(hours)*h/2,color='w',edgecolor='w',alpha=0.4,linewidth=0,bottom=base) pylab.bar(x[skip_first:],-1*Util.normalize(numpy.array(hill_increase[skip_first:]),set_max=set_hill_max)*h/2,color=spec,edgecolor=spec,bottom=base) pylab.plot(x[skip_first:],base-Util.normalize(numpy.cumsum(numpy.array(hill_increase[skip_first:])))*h/2*hill_scale_factor,'--w') for i,v in zip(x[skip_first:],Util.normalize(numpy.cumsum(numpy.array(hill_increase[skip_first:])))): if activity_percentile_plot and v > activity_percentile_plot: break pylab.plot((i,i),(base,base-(h/2)),'--w',lw=2) pylab.bar(x[skip_first:],Util.normalize(numpy.array(areas[skip_first:]),set_max=set_dig_max)*h/2,color=spec,edgecolor=spec,bottom=base) pylab.plot(x[skip_first:],base+Util.normalize(numpy.cumsum(numpy.array(areas[skip_first:])))*h/2*dig_scale_factor,'--w') for i,v in zip(x[skip_first:],Util.normalize(numpy.cumsum(numpy.array(areas[skip_first:])))): if activity_percentile_plot and v > activity_percentile_plot: break pylab.plot((i,i),(base,base+(h/2)),'--w',lw=2) if write_yval: pylab.text(5,base-h/2,'hill %0.1f' % max(hill_increase[skip_first:]),color='w') pylab.text(5,base+h/2,'dig %0.1f' % max(areas[skip_first:]),color='w') #''' for i, g in enumerate(grounds): pylab.plot(numpy.arange(hill_left,hill_right),g[hill_left:hill_right],c=spec[i]) #''' pylab.plot() pylab.ylim((1+graph_height)*SHAPE[0],0) pylab.xlim(0,SHAPE[1]) if outformat is not None: out_img = os.path.join(analysis_dir,outfile_prefix+'-activity_summary.'+outformat) print >> sys.stderr, 'save as %s' % out_img figobj.savefig(out_img) #VIDEO! spec = iplot.subspectrum(spectrum_len,noUV=True) if vid_fps: import cv vidout = os.path.join(analysis_dir,outfile_prefix+'-activity_summary.avi') if os.path.exists(vidout): os.unlink(vidout) pixdim = tuple(reversed(SHAPE)) pixdim = tuple(numpy.array(pixdim)*2) vidwriter = cv.CreateVideoWriter(vidout , cv.FOURCC('x','v','i','d'), vid_fps, pixdim,1) cols_polys = [] cols_hatch_polys = [] cols_lines = [] hourbar_kwargs = {'alpha':0.4,'linewidth':0} bars = [] bars.append(('w',(x,numpy.array(hours)*h/2,base,hourbar_kwargs))) bars.append(('w',(x,-1*numpy.array(hours)*h/2,base,hourbar_kwargs))) for vfi,m in enumerate(mouse_hists[1:]): if graph_height is not None: h = frames[0].shape[0] * graph_height m = numpy.array(list(m) + list(numpy.zeros((h,m.shape[1])))) if len(actouts[vfi]): cols_polys.extend(zip([spec[vfi]]*len(actouts[vfi]),actouts[vfi])) if post_summarize_analysis and len(config.get('predug',[])) > 0 and len(pdols[vfi]): cols_hatch_polys.extend(zip(['gray']*len(pdols[vfi]),['/']*len(pdols[vfi]),pdols[vfi])) cols_lines.append((spec[vfi],(numpy.arange(hill_left,hill_right),grounds[vfi][hill_left:hill_right]))) this_bars = [] #pylab.bar(x[skip_first:],-1*Util.normalize(numpy.array(hill_increase[skip_first:]))*h/2,color=spec,edgecolor=spec,bottom=base) this_bars.append((spec[:vfi],(x[:vfi],(-1*Util.normalize(numpy.array(hill_increase))*h/2)[:vfi],base,{}))) #pylab.plot(x[skip_first:],base-Util.normalize(numpy.cumsum(numpy.array(hill_increase[skip_first:])))*h/2,'--w') hi_line = [('w',(x[:vfi],(base-Util.normalize(numpy.cumsum(numpy.array(hill_increase)))*h/2)[:vfi]))] #pylab.bar(x[skip_first:],Util.normalize(numpy.array(areas[skip_first:]))*h/2,color=spec,edgecolor=spec,bottom=base) this_bars.append((spec[:vfi],(x[:vfi],(Util.normalize(numpy.array(areas))*h/2)[:vfi],base,{}))) #pylab.plot(x[skip_first:],base+Util.normalize(numpy.cumsum(numpy.array(areas[skip_first:])))*h/2,'--w') ba_line = [('w',(x[:vfi],(base+Util.normalize(numpy.cumsum(numpy.array(areas)))*h/2)[:vfi]))] cv_im = vidtools.mat_polys2cv(m,cols_polys,hatchpolys=cols_hatch_polys,lines=cols_lines+hi_line+ba_line,bars=bars+this_bars,scale=2) nll = cv.WriteFrame(vidwriter,cv_im) print >> sys.stderr, '\r\twrite video frame %s' % vfi,
g_col_li.append( (this_color, zip(*list(enumerate(Util.smooth(grounds[-1], 10)))))) last_frames_objs_ols = vidtools.ols_in_interval(frames_offset-hsl-1,frames_offset,min_arc_score,ols,ols_offset, \ Util.merge_dictlist([objs,to_retire_objs]), \ Util.merge_dictlist([objs_sizes,to_retire_objs_sizes]), \ Util.merge_dictlist([objs_fols,to_retire_objs_fols]), \ size_h, size_bins, fol_h, fol_bins,True) for vfi, m in enumerate(last_frames): if opts.antfarm_config: cv_im = vidtools.mat_polys2cv( m, zip( iplot.subspectrum(6)[1:], list(reversed(last_frames_objs_ols[vfi][:5]))) + zip(['k'] * len(prevol), prevol), zip([this_color] * len(digol), ['\\'] * len(digol), digol), g_col_li, 80, 2) else: cv_im = vidtools.mat_polys2cv( m, zip( iplot.subspectrum(6)[1:], list(reversed(last_frames_objs_ols[vfi][:5]))), [], [], 80, 2) nll = cv.WriteFrame(vidwriter, cv_im) print >> sys.stderr, '\r\twrite video frame %s' % vfi, retire_objs(ols_offset - hsl, to_retire_objs, to_retire_objs_sizes, to_retire_objs_fols, retired_objs, retired_objs_sizes,