def plot_likelihoods( p, name, score = None ): from pylab import plot, show, cla, clf, legend, figure, xlabel, ylabel, \ title, axvspan old_odds = PssmParameters.singleton().binding_background_odds_prior PssmParameters.singleton().binding_background_odds_prior = 1.0 ( bind, back, cum_bind, cum_back, odds_ratio, cum_odds_ratio, p_bind, cum_p_bind, p_value_p_bind ) = get_pssm_likelihoods( p ) scores = [ float(i) / (len(bind) - 1.0) for i in range( len( bind ) ) ] # cla() # clf() figure() plot( scores, bind, 'g-', label='binding' ) plot( scores, back, 'b-', label='background' ) plot( scores, cum_bind, 'g--', label='binding (cumulative)' ) plot( scores, cum_back, 'b--', label='background (cumulative)' ) plot( scores, p_bind, 'r-', label='p(binding)' ) plot( scores, cum_p_bind, 'r--', label='p(binding) (cumulative)' ) plot( scores, p_value_p_bind, 'y--', label='p(binding) (p-value)' ) # legend( loc='center left' ) xlabel( 'score' ) title( name ) if score: idx = get_likelihood_index( len( bind ), score ) axvspan( score, score ) show() PssmParameters.singleton().binding_background_odds_prior = old_odds
def plot_exclude(): global exclude #c = '#FFFFFF' c = '#DDDDDD' #c = 'g' for l,u in exclude: pl.axvspan(l,u, fc=c, ec=c)
def _decorate_histogram(vstats): import pylab from matplotlib.transforms import blended_transform_factory as blend # Shade things inside 1-sigma pylab.axvspan(vstats.p68[0],vstats.p68[1], color='gold',alpha=0.5,zorder=-1) # build transform with x=data, y=axes(0,1) ax = pylab.gca() transform = blend(ax.transData, ax.transAxes) l95,h95 = vstats.p95 l68,h68 = vstats.p68 def marker(s,v): if v < l95: s,v,ha = '<'+s,l95,'left' elif v > h95: s,v,ha = '>'+s,h95,'right' else: ha='center' pylab.text(v, 0.95, s, va='top', ha=ha, transform=transform, zorder=3, color='g') #pylab.axvline(v) marker('|',vstats.median) marker('E',vstats.mean) marker('*',vstats.best) pylab.text(0.01, 0.95, vstats.label, zorder=2, backgroundcolor=(1,1,0,0.2), verticalalignment='top', horizontalalignment='left', transform=pylab.gca().transAxes) pylab.setp([pylab.gca().get_yticklabels()],visible=False) ticks = (l95, l68, vstats.median, h68, h95) labels = [format_value(v,h95-l95) for v in ticks] if len(labels[2]) > 5: # Drop 68% values if too many digits ticks,labels= ticks[0::2],labels[0::2] pylab.xticks(ticks, labels)
def annotated_plot(v,normfiltfunc,a,e):#plots a the Hotspot along with the annotated regions from the posterior decoding import pylab v2 = normfiltfunc(v) (s,f,b,pdf_m) = posterior_step(v2,a,e) post = s*f*b maxstates = post.argmax(axis=0) #label the footprints foots = (maxstates == 3)*1 bins = diff(foots) start = where(bins == 1)[0] + 1 stop = where(bins == -1)[0] for p,q in zip(start,stop): foot = pylab.axvspan(p, q, facecolor='r', alpha=0.5) #label the HS1 hs1s = (maxstates == 0)*1 bins = diff(hs1s) start = concatenate(([0],where(bins == 1)[0] + 1),1)#the first state is hs1. this accounts for that stop = where(bins == -1)[0] for p,q in zip(start,stop): hs1 = pylab.axvspan(p, q, facecolor='g', alpha=0.5) #label the HS2 hs2s = (maxstates == 4)*1 bins = diff(hs2s) start = where(bins == 1)[0] + 1 stop = concatenate((where(bins == -1)[0],[len(v)-1]),1)#the last state is hs2 for p,q in zip(start,stop): hs2 = pylab.axvspan(p, q, facecolor='c', alpha=0.5) pylab.plot(v) pylab.legend((hs1,foot,hs2,),('HS1','Footprint','HS2',)) pylab.xlabel('DHS Coordinates') pylab.ylabel('DNase I Cuts')
def BinnedChroPlot(initial, final, binsize=100, CenShading=[CenStart,CenEnd], name='Chromosome'): ''' This function creates a graph of initial and final Chromosomes binned per (binsize) ''' Title = '%s usage, binned per %i'%(name,binsize) plt.figure(Title) plt.title(Title) global initialHeights initialSize = len(initial)/binsize finalSize = len(final)/binsize initialHeights = [sum(initial[x:x+binsize]) for x in xrange(0,len(initial),binsize)] # idem, but binned in bargraph[x:x+binsize]) for x in xrange(0,ChroL,binsize)] #create binned initial Chro finalHeights = [sum(final[x:x+binsize]) for x in xrange(0,len(final),binsize)] #create binned Chro if CenShading: if CenShading == [CenStart,CenEnd]: CenShading = [CenStart/binsize,CenEnd/binsize] plt.axvspan(CenShading[0], CenShading[1], color='0.85') plt.bar(xrange(initialSize), initialHeights, lw=0, width=1, color='r', label='initial', alpha=0.4) plt.bar(xrange(finalSize), finalHeights, lw=0, width=1, color='b', label='final', alpha=0.4) plt.ylabel('sites occupied (of %i)'%(binsize)) plt.xlabel('bin number (%i sites per bin)'%(binsize)) plt.legend() plt.show()
def plot(self): f = pylab.figure(figsize=(8,4)) co = [] #colors container for zScore, r in itertools.izip(self.zScores, self.log2Ratio): if zScore < self.pCut: if r > 0: co.append(Colors().greenColor) elif r < 0: co.append(Colors().redColor) else: raise Exception else: co.append(Colors().blueColor) #print "Probability this is from a normal distribution: %.3e" %stats.normaltest(self.log2Ratio)[1] ax = f.add_subplot(121) pylab.axvline(self.meanLog2Ratio, color=Colors().redColor) pylab.axvspan(self.meanLog2Ratio-(2*self.stdLog2Ratio), self.meanLog2Ratio+(2*self.stdLog2Ratio), color=Colors().blueColor, alpha=0.2) his = pylab.hist(self.log2Ratio, bins=50, color=Colors().blueColor) pylab.xlabel("log2 Ratio %s/%s" %(self.sampleNames[1], self.sampleNames[0])) pylab.ylabel("Frequency") ax = f.add_subplot(122, aspect='equal') pylab.scatter(self.genes1, self.genes2, c=co, alpha=0.5) pylab.ylabel("%s RPKM" %self.sampleNames[1]) pylab.xlabel("%s RPKM" %self.sampleNames[0]) pylab.yscale('log') pylab.xscale('log') pylab.tight_layout()
def draw_search_graph(plots): import pylab as pl fg = pl.figure() ax = fg.add_subplot(111) ax.yaxis.set_major_formatter(pl.FuncFormatter(labelfmt)) for (values, attrs) in plots: indexes, width = pl.arange(len(values)), 1.0 / len(plots) yvalues = [x.result for x in values] xoffset = width * plots.index((values, attrs)) ax.plot(indexes + xoffset, yvalues, **attrs) legend = ax.legend(loc='best') legend.get_frame().set_alpha(0.6) fg.canvas.draw() pl.ylabel('tradeoff improvement -->') pl.xlabel('number of tested configurations -->') pl.title('Search Graph') pl.axhspan(0.0, 0.0) pl.axvspan(0.0, 0.0) pl.grid(True) pl.show()
def search_clusters(self, data): """This function performs the search for significant clusters. Uses a class from eegpy.stats.cluster """ plotid=0 for i_ch in range(data[0].shape[2]): for i_b in range(data[0].shape[3]): #print i_ch,i_b cs_data = [d[:,:,i_ch,i_b].T for d in data] #print len(cs_data), [csd.shape for csd in cs_data] fs,sct,scp,ct,cp = ClusterSearch1d(cs_data,num_surrogates=self._num_surrogates).search() #print "CPM: fs.shape=",fs.shape #print ct, cp for i_c in range(len(sct)): self._clusters.append( (i_ch,i_b,sct[i_c],scp[i_c]) ) #Do plot if significant cluster found if len(sct)>0: #print "CPM: fs.shape=",fs.shape, fs.dtype #print "CPM: fs[499:510]", fs[498:510] p.plot(np.array(fs)) p.title("Channel %i, band %i"%(i_ch,i_b)) for cluster in sct: p.axvspan(cluster[0],cluster[1],color="y",alpha=0.2) p.savefig("/tmp/fbpm%03d.png"%plotid) plotid+=1 p.clf()
def draw_onsets(onsets): if not onsets: return # Draw the onsets for onsetLeft, onsetCenter, onsetRight in onsets: pylab.axvspan( xmin = onsetLeft, xmax = onsetRight, facecolor = 'green', linewidth = 0, alpha = 0.25) pylab.axvline( x = onsetCenter, color = 'black', linewidth = 1.1)
def plotRes(data, errors, r): import pylab pylab.figure() nObs = len(data) n, bins, patches = pylab.hist(data, 2*np.sqrt(nObs), fc=[.7,.7,.7]) binSize = bins[1] - bins[0] x = np.arange(bins[0], bins[-1]) means, sigs, pis, mVars, weights = r inds = np.argmax(weights, 1) for i in range(means.size): #print i c = pylab.cm.hsv(float(i)/means.size) n, bin_s, patches = pylab.hist(data[inds == i], bins, alpha=0.3, facecolor=c) ys = np.zeros_like(x) i = 0 for m, s, p in zip(means, sigs, pis): c = pylab.cm.hsv(float(i)/means.size) y = nObs*p*binSize*np.exp(-(x-m)**2/(2*s**2))/np.sqrt(2*np.pi*s**2) ys += y i+= 1 pylab.plot(x,y, lw=2, color=c) #pylab.plot(x, ys, lw=3) pylab.figure() ci = (r[4]*np.arange(r[0].size)[None,:]).sum(1) I = np.argsort(ci) cis = ci[I] cil = 0 for i in range(means.size): c = pylab.cm.hsv(float(i)/means.size) print(c) pylab.axvline(means[i], color=c) pylab.axvspan(means[i] - sigs[i], means[i] + sigs[i], alpha=0.5, facecolor=c) cin = cis.searchsorted(i+0.5) pylab.axhspan(cil, cin, alpha=0.3, facecolor=c) cil = cin pylab.errorbar(data[I], np.arange(data.size), xerr=errors[I], fmt='.')
def plot_tree(T, res=None, title=None, cmap_id="Pastel2"): """Plots a given tree, containing hierarchical segmentation. Parameters ---------- T: mir_eval.segment.tree A tree object containing the hierarchical segmentation. res: float Frame-rate resolution of the tree (None to use seconds). title: str Title for the plot. `None` for no title. cmap_id: str Color Map ID """ def round_time(t, res=0.1): v = int(t / float(res)) * res return v # Get color map cmap = plt.get_cmap(cmap_id) # Get segments by level level_bounds = [] for level in T.levels: if level == "root": continue segments = T.get_segments_in_level(level) level_bounds.append(segments) # Plot axvspans for each segment B = float(len(level_bounds)) #plt.figure(figsize=figsize) for i, segments in enumerate(level_bounds): labels = utils.segment_labels_to_floats(segments) for segment, label in zip(segments, labels): #print i, label, cmap(label) if res is None: start = segment.start end = segment.end xlabel = "Time (seconds)" else: start = int(round_time(segment.start, res=res) / res) end = int(round_time(segment.end, res=res) / res) xlabel = "Time (frames)" plt.axvspan(start, end, ymax=(len(level_bounds) - i) / B, ymin=(len(level_bounds) - i - 1) / B, facecolor=cmap(label)) # Plot labels L = float(len(T.levels) - 1) plt.yticks(np.linspace(0, (L - 1) / L, num=L) + 1 / L / 2., T.levels[1:][::-1]) plt.xlabel(xlabel) if title is not None: plt.title(title) plt.gca().set_xlim([0, end])
def plot_labels(all_labels, gt_times, est_file, algo_ids=None, title=None, output_file=None): """Plots all the labels. Parameters ---------- all_labels: list A list of np.arrays containing the labels of the boundaries, one array for each algorithm. gt_times: np.array Array with the ground truth boundaries. est_file: str Path to the estimated file (JSON file) algo_ids : list List of algorithm ids to to read boundaries from. If None, all algorithm ids are read. title : str Title of the plot. If None, the name of the file is printed instead. """ N = len(all_labels) # Number of lists of labels if algo_ids is None: algo_ids = io.get_algo_ids(est_file) # Translate ids for i, algo_id in enumerate(algo_ids): algo_ids[i] = translate_ids[algo_id] algo_ids = ["GT"] + algo_ids # Index the labels to normalize them for i, labels in enumerate(all_labels): all_labels[i] = mir_eval.util.index_labels(labels)[0] # Get color map cm = plt.get_cmap('gist_rainbow') max_label = max(max(labels) for labels in all_labels) # To intervals gt_inters = utils.times_to_intervals(gt_times) # Plot labels figsize = (6, 4) plt.figure(1, figsize=figsize, dpi=120, facecolor='w', edgecolor='k') for i, labels in enumerate(all_labels): for label, inter in zip(labels, gt_inters): plt.axvspan(inter[0], inter[1], ymin=i / float(N), ymax=(i + 1) / float(N), alpha=0.6, color=cm(label / float(max_label))) plt.axhline(i / float(N), color="k", linewidth=1) # Draw the boundary lines for bound in gt_times: plt.axvline(bound, color="g") # Format plot _plot_formatting(title, est_file, algo_ids, gt_times[-1], N, output_file)
def test_empty_datetime( self ): """Test plotting empty axes with dates along one axis.""" fname = self.outFile( "empty_datetime.png" ) t0 = datetime(2009, 1, 20) tf = datetime(2009, 1, 21) fig = pylab.figure() pylab.axvspan( t0, tf, facecolor="blue", alpha=0.25 ) fig.autofmt_xdate() fig.savefig( fname ) self.checkImage( fname )
def plot_one_track(file_struct, est_times, est_labels, boundaries_id, labels_id, title=None): """Plots the results of one track, with ground truth if it exists.""" # Set up the boundaries id bid_lid = boundaries_id if labels_id is not None: bid_lid += " + " + labels_id try: # Read file jam = jams.load(file_struct.ref_file) ann = jam.search(namespace='segment_.*')[0] ref_inters, ref_labels = ann.data.to_interval_values() # To times ref_times = utils.intervals_to_times(ref_inters) all_boundaries = [ref_times, est_times] all_labels = [ref_labels, est_labels] algo_ids = ["GT", bid_lid] except: logging.warning("No references found in %s. Not plotting groundtruth" % file_struct.ref_file) all_boundaries = [est_times] all_labels = [est_labels] algo_ids = [bid_lid] N = len(all_boundaries) # Index the labels to normalize them for i, labels in enumerate(all_labels): all_labels[i] = mir_eval.util.index_labels(labels)[0] # Get color map cm = plt.get_cmap('gist_rainbow') max_label = max(max(labels) for labels in all_labels) figsize = (8, 4) plt.figure(1, figsize=figsize, dpi=120, facecolor='w', edgecolor='k') for i, boundaries in enumerate(all_boundaries): color = "b" if i == 0: color = "g" for b in boundaries: plt.axvline(b, i / float(N), (i + 1) / float(N), color=color) if labels_id is not None: labels = all_labels[i] inters = utils.times_to_intervals(boundaries) for label, inter in zip(labels, inters): plt.axvspan(inter[0], inter[1], ymin=i / float(N), ymax=(i + 1) / float(N), alpha=0.6, color=cm(label / float(max_label))) plt.axhline(i / float(N), color="k", linewidth=1) # Format plot _plot_formatting(title, os.path.basename(file_struct.audio_file), algo_ids, all_boundaries[0][-1], N, None)
def draw_correl_graph(getgraph, opts): # http://matplotlib.sourceforge.net/index.html fg = pl.figure() ax = fg.add_subplot(111) bars = getgraph() for (values, attrs) in bars: indexes, width = pl.arange(len(values)), 1.0 / len(bars) yvalues = [x.speedup for x in values] xoffset = width * bars.index((values, attrs)) ax.bar(indexes + xoffset, yvalues, width, picker=4000, **attrs) ax.legend(loc='lower left') fg.canvas.draw() # dynamic annotations def on_pick(event): ind = int(event.mouseevent.xdata) point = bars[0][0][ind] tooltip.set_position( (event.mouseevent.xdata, event.mouseevent.ydata)) tooltip.set_text(point_descr(point)) tooltip.set_visible(True) fg.canvas.draw() tooltip = ax.text( 0, 0, "undef", bbox=dict(facecolor='white', alpha=0.8), verticalalignment='bottom', visible=False) # graph title try: title = 'Correlation Graph for %s' % ( opts.id or opts.targets or bars[0][0][0].target) except: title = 'Correlation Graph' # redraw axis, set labels, legend, grid, ... def labelfmt(x, pos=0): return '%.2f%%' % (100.0 * x) ax.yaxis.set_major_formatter(pl.FuncFormatter(labelfmt)) pl.ylabel('speedup (higher is better) -->') pl.xlabel('Configurations (ordered by decreasing speedup of ' + bars[0][1]['label'] + ') -->') pl.title(title) pl.axhspan(0.0, 0.0) pl.axvspan(0.0, 0.0) pl.grid(True) if opts.outfile: fg.savefig(opts.outfile) if opts.show: fg.canvas.mpl_connect('pick_event', on_pick) pl.show()
def csv2png(p): print p title, axis, data = get_data(p) dates = data[0] release_title, release_axis, release_data = get_data( py.path.local("release_dates.dat") ) release_dates, release_names = release_data sprint_title, sprint_axis, sprint_data = get_data( py.path.local("sprint_dates.dat") ) sprint_locations, sprint_begin_dates, sprint_end_dates = sprint_data ax = pylab.subplot(111) for i, d in enumerate(data[1:]): args = [dates, d, colors[i]] pylab.plot_date(linewidth=0.8, *args) ymax = max(pylab.yticks()[0]) #just below the legend for i, release_date in enumerate(release_dates): release_name = release_names[i] if greyscale: color = 0.3 else: color = "g" pylab.axvline(release_date, linewidth=0.8, color=color, alpha=0.5) ax.text(release_date, ymax * 0.4, release_name, fontsize=10, horizontalalignment='right', verticalalignment='top', rotation='vertical') for i, location in enumerate(sprint_locations): begin = sprint_begin_dates[i] end = sprint_end_dates[i] if float(begin) >= float(min(dates[0],dates[-1])): if greyscale: color = 0.8 else: color = "y" pylab.axvspan(begin, end, linewidth=0, facecolor=color, alpha=0.5) ax.text(begin, ymax * 0.85, location, fontsize=10, horizontalalignment='right', verticalalignment='top', rotation='vertical') pylab.legend(axis[1:], "upper left") pylab.ylabel(axis[0]) pylab.xlabel("") ticklabels = ax.get_xticklabels() pylab.setp(ticklabels, 'rotation', 45, size=9) # ax.autoscale_view() ax.grid(True) pylab.title(title) pylab.savefig(p.purebasename + ".png") pylab.savefig(p.purebasename + ".eps") py.process.cmdexec("epstopdf %s" % (p.purebasename + ".eps", ))
def test_axvspan_epoch(self): """Test the axvspan method with Epochs.""" fname = self.outFile("axvspan_epoch.png") t0 = units.Epoch("ET", dt=datetime(2009, 1, 20)) tf = units.Epoch("ET", dt=datetime(2009, 1, 21)) dt = units.Duration("ET", units.day.convert("sec")) fig = pylab.figure() pylab.axvspan(t0, tf, facecolor="blue", alpha=0.25) ax = pylab.gca() ax.set_xlim(t0 - 5.0 * dt, tf + 5.0 * dt) fig.savefig(fname) self.checkImage(fname)
def test_axvspan_epoch(): from datetime import datetime import matplotlib.testing.jpl_units as units units.register() t0 = units.Epoch( "ET", dt=datetime(2009, 1, 20) ) tf = units.Epoch( "ET", dt=datetime(2009, 1, 21) ) dt = units.Duration( "ET", units.day.convert( "sec" ) ) fig = pylab.figure() pylab.axvspan( t0, tf, facecolor="blue", alpha=0.25 ) ax = pylab.gca() ax.set_xlim( t0 - 5.0*dt, tf + 5.0*dt ) fig.savefig( 'axvspan_epoch' )
def plot_stiff_area(bin_f0, B, bin_spread_below, bin_spread_above, stiff_partials, sample_rate): stiff_bins = numpy.array( [ partials.mode_B2freq( bin_f0, i+1, B) for i in xrange(len(stiff_partials)) ] ) for i, est in enumerate(stiff_bins): low = stft.bin2hertz(est - bin_spread_below, sample_rate) high = stft.bin2hertz(est + bin_spread_above, sample_rate) if i == 0: pylab.axvspan(low, high, color='c', alpha=0.3, label="stiff") else: pylab.axvspan(low, high, color='c', alpha=0.3)
def plotGait2(self, graphNumber=1, background='gray', lineWidth=10): graph = self._figure.add_subplot(self._numberRows, 1, graphNumber) self.setBackground(background) rect = graph.patch rect.set_facecolor(background) y_RH, y_RF, y_LF, y_LH = 0.2, 0.4, 0.6, 0.8 stop = self._cd.configs.get(GeneralConfigEnum.STOP_TIME) start = self._cd.configs.get(GeneralConfigEnum.START_TIME) steps = self._cd.configs.get(GeneralConfigEnum.STEPS) delta = (stop - start)/steps times = plt.arange(self._plotStartTime, self._plotStopTime, delta) valuesRH = self.values(self._channel_RH, times) valuesRF = self.values(self._channel_RF, times) valuesLF = self.values(self._channel_LF, times) valuesLH = self.values(self._channel_LH, times) self.setColorMap('RdYlGn') for i in range(len(times)): time = times[i] lh, lf, rf, rh = valuesLH[i], valuesLF[i], valuesRF[i], valuesRH[i] if lh and lf and rf and rh: support = 1.0 elif (lh and rf and rh) or (lh and lf and rh): support = 0.95 elif (lh and lf and rf) or (lf and rf and rh): support = 0.85 elif lh and rh: support = 0.75 elif (lh and rf) or (lf and rh): support = 0.7 elif lf and rf: support = 0.2 elif (lh and lf) or (rf and rh): support = 0.1 else: support = 0.0 if support > 0.0: plt.axvspan(time - 2.0*delta, time, fc=self.mapValueToColor(support), ec='none') self.setColorMap('gray') self.plotChannel(self._channel_LH, graph, y_LH, lineWidth) self.plotChannel(self._channel_LF, graph, y_LF, lineWidth) self.plotChannel(self._channel_RF, graph, y_RF, lineWidth) self.plotChannel(self._channel_RH, graph, y_RH, lineWidth) plt.xlim([self._plotStartTime, self._plotStopTime - 1]) plt.ylim(0, 1) positions = (y_RH, y_RF, y_LF, y_LH) labels = ('Right Hind', 'Right Fore', 'Left Fore','Left Hind') plt.yticks(positions, labels) return True
def format_data(name, data, offset=0): currently = 0 changes = [] for x in data: start = x.tick if x.hist.caught_at > 0: p.axvspan( x.hist.caught_at, x.hist.caught_at + x.duration, alpha=0.25, label="Processing " + name, color="red" ) if currently != x.value.digital: changes.append((start, offset + currently)) changes.append((start, offset + x.value.digital)) currently = x.value.digital return changes
def plot_fit_and_tails(closeness, title): """Plot closeness centrality distribution, fit Gauss and mark outermosts and leaders areas in plot""" P.suptitle(title) m, sd = np.mean(closeness), np.std(closeness) outer = m - sd if outer > 0: P.axvspan(0, outer, alpha=0.2, color='c', label="Outermosts") leaders = m + sd if leaders < 1: P.axvspan(leaders, 0.2, alpha=0.2, color='y', label="Leaders") P.hist(closeness, color='#AB717A') x = np.linspace(0, 0.2) P.plot(x, mlab.normpdf(x, m, sd), '--', color='k') # P.xticks(np.arange(0, 0.2, 0.01)) P.legend()
def ChroPlot(initial,final): ''' This function creates a graph of initial and final Chromosomes''' Title = 'Chromosome usage' plt.figure(Title) plt.title(Title) plt.plot(initial, 'r', lw=.05, label='initial') plt.plot(final, 'b', lw=.05, label='final') plt.axvspan(CenStart, CenEnd, color='none', lw=1.3, ec='k') plt.ylabel('CA') plt.xlabel('site') #plt.legend() #labels invisible due to extremely thin lines plt.show()
def OccupancyPlot(fracs): ''' This function creates a graph of how often each position has been used throughout all divisions''' Title = 'Chromosome occupancy per site' plt.figure(Title) plt.title(Title) x = xrange(ChroL) y = fracs plt.axvspan(CenStart, CenEnd, color='b', alpha=0.5, lw=0) plt.bar(x, y, lw=0, width=1, color='black') plt.xlabel('Nucleosome position') plt.ylabel('Times occupied (in %i cycles)'%(divs)) plt.axis([0, ChroL, 0, 1]) plt.show()
def coo(self,tmin,tmax): self.lims = [tmin,tmax] if self.boxh: self.boxh.remove() if self.direction is 'horizontal': self.boxh = pl.axvspan(tmin,tmax,facecolor='r',alpha=0.5) if self.direction is 'vertical': self.boxh = pl.axhspan(tmin,tmax,facecolor='r',alpha=0.5) fig.canvas.draw()
def TTteachFilter(profiles,): from scipy.linalg import toeplitz nfh = tools.nfigure('Digital filter design: Select signal') pl.clf() p = profiles[2,:] pl.plot(p) siglim = np.round(tools.getSpanCoordinates('horizontal')) #print 'Select step position of step' #stepoffs = pl.ginput(1)[0][0]-np.mean(siglim) #pl.axvline(stepoffs+np.mean(siglim),color='r') ys = p[siglim[0]:siglim[1]] ysacl = np.correlate(ys,ys,'same') sacl = ysacl nfh = tools.nfigure('Digital filter design: Select noise region') pl.clf() pl.plot(profiles.transpose()) logbook("select lower limit of noise area (NB: has same width as signal range!)") noiselim = pl.ginput(1) noiselim = round(noiselim[0][0])+np.array([0,np.diff(np.array(siglim))[0]]) pl.axvspan(noiselim[0],noiselim[1],facecolor='r',alpha=0.5) pl.axvline(noiselim[0],color='r') pl.axvline(noiselim[1],color='r') logbook(noiselim) nacl = [] for p in profiles: yn = p[noiselim[0]:noiselim[1]] ynacl = np.correlate(yn,yn,'same') nacl.append(ynacl) nacl = np.mean(np.vstack(nacl),axis=0) Ynacl = toeplitz(nacl,r=np.zeros(len(nacl))) R = np.matrix(Ynacl).I Rs = np.matrix(sacl) weights = R*Rs.transpose() weights = np.array(weights).ravel() weights = weights-np.median(weights) filtsettings = dict(weights=np.array(weights), #stepoffs=stepoffs, noise_limits=noiselim) return filtsettings
def plotpdf(name, data, weights, label, xmin, xmax, bestfit, bdelta=0.1): """ make pdf plots for age, av, and z inputs: cluster name; array of parameters (age, av, or z) from matchoutput file; fit values from matchoutput file; string name of parameter; minimum value of parameter to plot; maximum value of parameter to plot; best fit value of parameter; bin size output: apXXX/apXXX_XXXptiles.txt""" hdelta=bdelta/2. nbins=np.around((data.max()-data.min())/bdelta)+1 xbins=np.linspace(np.around(data.min()-hdelta,3),np.around(data.max()+bdelta+hdelta,3),nbins+2) #calculate bins h = np.histogram(data, bins=xbins, weights=weights) #create histogram of data hist = h[0]/np.sum(h[0]) #normalize histogram ptiles = output.weighted_percentile(data, weights, [0.16, 0.5, 0.84]) #compute percentiles np.savetxt(name+'/'+name+'_'+label+'ptiles.txt', ptiles) #save these weighted percentiles plt.axvspan(ptiles[0], ptiles[2], color='0.8', alpha=0.5) plt.step(np.linspace(data.min(), data.max(), len(h[0])), hist, color='black', lw=3) plt.axvline(ptiles[1], color='r', lw=2) plt.axvline(bestfit, color='b', lw=2) plt.ylim(np.min(hist.min(), 0), hist.max()*1.05) plt.xlim(xmin, xmax) plt.xlabel(label)
def histogram(dane,przedz=0,krok=1,norm=0,sig=0,sr=0,dop=0,wys=0,osX=0,osY=0,tyt=0,fs='x-large'): '''Rysuje histogram nie wyswietlajac go - potrzeba zakonczyc py.show(). dane - wektor danych (krotka/lista/array) przedz - przedzial do narysowania (lista/array) krok - krok histogramowania (int/float) norm - normalizowac? 'g'estosc / 'c'zestosc / False sig - rysowac zakresy ilu sigm? (int/float) sr - pokazac srednia? (True/False) dop - dopasuj funkcje - 0/'gauss' - dziala przy norm=0 lub 'g' wys - wysokosc histogramu, 0 - policzy sam (int/float) osX - podpis osi X (str) osY - podpis osi Y (str) tyt - tytul (str) fs - fontsize (str/int)''' if not bool(przedz): przedz = np.arange(min(dane),max(dane)+krok,krok) # Jezeli przedzialy nie istnieja, generuje sam if norm=='c': wagi = [1./len(dane)] * len(dane) # Jezeli normuje wg czestosci, liczy wagi (moglby tez mnozyc gestosci, ale to kiedy indziej) else: wagi = [1.]*len(dane) if norm=='g': gest = True else: gest = False if wys!=0: py.ylim((0,wys)) # Ustawia wysokosc, jezeli istnieje py.xlim((min(dane)-krok/2,max(dane)+krok/2)) # Ogranicza X do min i max wartosci + pol kroku py.hist(dane,bins=przedz,weights=wagi,normed=gest,color='gray') # Rysowanie histogramu py.xticks(rotation=45,size=fs) # wielkosc czcionki, wartosci pod katem py.yticks(size=fs) # tylko wielkosc czcionki if sr!=0: py.axvline(np.mean(dane),color='black') # srednia if sig!=0: #przedzialy ufnosci sigma = sig*np.std(dane) # szerokosc (sig) sigm msig,Msig = np.mean(dane)-sigma,np.mean(dane)+sigma # skad dokad sigmy py.axvspan(msig,Msig,alpha=.25) # rysowanie spanu procent = sum(map(lambda d: msig < d <= Msig,dane)) / float(len(dane)) #automatycznie liczy, ile procent danych znajduje sie w przedziale print "W przedziale", sigma, "znajduje sie", procent py.grid(True) # rysuje siatke if tyt!=0: py.title(tyt,family='serif',size=fs) # ustawia tytul, jezeli istnieje if osX!=0: py.xlabel(osX,family='serif',size=fs) if osY!=0: py.ylabel(osY,family='serif',size=fs) if dop=='gauss': #dopasowuje gaussa from scipy.stats import norm wek = norm.fit(dane) # wek wynosi [miu,sigma] ze wzoru dopasowania osG = np.linspace(py.xlim()[0],py.xlim()[1],100) # generuje nowa gestsza os X, na ktorej narysuje gaussa fit = norm.pdf(osG,loc=wek[0],scale=wek[1]) # tworzy os Y gaussa py.plot(osG,fit*((krok*len(dane))**(1-gest)),color='black') # i w koncu go rysuje
def plotHM80(): # data from Hoessel & Melnick 1980 Table 1 g = np.array([17.04,17.54,17.98,18.33,18.6,18.84,19.07,19.26,19.41,19.59,19.73,19.86,19.97,20.09,20.16,20.23,20.38,20.46,20.52,20.58,20.47,19.86,20.,20.82,20.85,20.91,20.96,20.95,20.97,21.,20.93,20.92,21.06,21.1,21.13,21.18,21.2,21.23,21.28,21.3,21.34,21.42,21.42,21.45,21.5,21.54,21.57,21.78,21.88,21.89,21.84,21.83,21.79,21.8,21.9,21.89,22.02,22.04,22.06,21.89,21.92,22.07,22.19,22.21,22.13,22.12,22.16,22.16,22.11,22.1,22.13,22.13,22.14,22.05,22.06,22.12,22.15,22.17,22.25,22.34,22.39,22.33,27.08,22.16,22.19,22.18,22.03,21.81,21.57,21.43,21.51,21.61,21.76,21.68,21.81,21.98,22.32]) gr=np.array([.56,.57,.55,.55,.56,.57,.56,.57,.57,.56,.56,.54,.54,.55,.52,.53,.55,.53,.52,.52,.39,.08,.24,.65,.53,.55,.56,.53,.53,.53,.45,.48,.53,.5,.49,.51,.5,.5,.52,.5,.52,.53,.49,.5,.5,.49,.51,.59,.56,.54,.47,.5,.47,.46,.53,.48,.57,.58,.54,.45,.56,.63,.63,.57,.5,.53,.58,.53,.48,.53,.54,.52,.51,.48,.53,.51,.51,.59,.59,.65,.61,.56,.44,.54,.49,.49,.34,.27,.17,.25,.33,.34,.39,.33,.43,.51,.57]) r=g-gr # in arcsec rad=np.arange(13.1,2555.,26.3) py.plot(rad,g,'go') py.plot(rad,r,'ro') py.axvspan(5.5,300,facecolor='c',alpha=.5) py.legend(('G','R','KB99 bulge range')) py.ylim(23,16) py.xlim(0,2500) py.xlabel('arcsec') py.ylabel('$\mu$ (mag arcsec$^{-2}$)') py.title('Hoessel and Melnick 1980, Palomar obs')
def draw_shannon_distrib(neut_h, obs_h, out, pval=1): ''' draws distribution of Shannon values for random neutral :argument neut_h: list of Shannon entropies corresponding to simulation under neutral model :argument obs_h: Shannon entropy of observed distribution of abundance ''' neut_h = np.array ([float (x) for x in neut_h]) obs_h = float (obs_h) pylab.hist(neut_h, 40, color='green', histtype='bar', fill=True) pylab.axvline(float(obs_h), 0, color='r', linestyle='dashed') pylab.axvspan (float(obs_h) - neut_h.std(), float(obs_h) + neut_h.std(), facecolor='orange', alpha=0.3) pylab.xlabel('Shannon entropy (H)') pylab.ylabel('Number of observations over %s simulations' % (len (neut_h))) pylab.title("Histogram of entropies from %s simulations compared to \nobserved entropy (red), deviation computed from simulation, p-val=%.5f" % (len (neut_h),pval)) F = pylab.gcf() DPI = F.get_dpi() F.set_size_inches ( (15.0,17.0)) F.savefig (out, dpi=DPI+30, format='png') pylab.close()
def estimate_f0_B(filenames): ### ASSUME: all filenames are of the same instrument-string wav_filename = filenames[0] basename = '-'.join(os.path.basename(wav_filename).split('-')[0:3]) if basename.startswith("test-440f"): return 440.0, 0, 1, 1, 1, 1 ### get initial f0 estimate base_frequency_estimate = expected_frequencies.get_freq_from_filename( wav_filename) ### get noise initial_noise_floor, initial_noise_freqs, _, _, _ = calc_noise.get_noise( wav_filename) noise_cutoff = stft.db2amplitude( stft.amplitude2db(initial_noise_floor) + defs.B_MINIMUM_HARMONIC_SNR) #### get FFT frames from audio files sample_rate = None freqs = None estimate_B_buffers_list = [] for wav_i, wav_filename in enumerate(filenames): #print wav_filename #window_buffer, sample_rate = stft.get_long_buffer_from_file(wav_filename, window_buffers, sample_rate = stft.get_buffers_from_file( wav_filename, (defs.B_NUM_BUFFERS_ESTIMATE)) if freqs is None: freqs = [ stft.bin2hertz(i, sample_rate) for i in range(stft.WINDOWSIZE / 2 + 1) ] estimate_B_buffers_this_list = [] #fft_amplitude = stft.fft_amplitude(window_buffer, sample_rate) #estimate_B_buffers_this_list.append(fft_amplitude) for window_number in range(defs.B_NUM_BUFFERS_ESTIMATE): window_buffer = window_buffers[window_number] fft_amplitude = stft.stft_amplitude(window_buffer) estimate_B_buffers_this_list.append(fft_amplitude) estimate_B_buffers_list.extend(estimate_B_buffers_this_list) estimate_B_buffers = numpy.array(estimate_B_buffers_list) ### radius of search area for peaks # used with STFT only bin_initial_estimate = stft.hertz2bin(base_frequency_estimate, sample_rate) #bin_initial_estimate = (base_frequency_estimate # * fft_amplitude.shape[0] / (sample_rate/2) # ) #print bin_initial_estimate bin_spread_below = int( math.ceil( abs( stft.hertz2bin((1.0 - defs.B_PEAK_SPREAD_BELOW_HERTZ) * base_frequency_estimate, sample_rate) - bin_initial_estimate))) bin_spread_above = int( math.ceil( stft.hertz2bin((1.0 + defs.B_PEAK_SPREAD_ABOVE_HERTZ) * base_frequency_estimate, sample_rate) - bin_initial_estimate)) #bin_spread_below = int(round(bin_initial_estimate * # defs.B_PEAK_SPREAD_BELOW_HERTZ)) #bin_spread_above = int(round(bin_initial_estimate * # defs.B_PEAK_SPREAD_BELOW_HERTZ)) #bin_spread_below_main = int( # stft.hertz2bin(defs.STFT_PEAK_SPREAD_BELOW_HERTZ*base_frequency_estimate, # sample_rate)) #bin_spread_above_main = int( # stft.hertz2bin(defs.STFT_PEAK_SPREAD_ABOVE_HERTZ*base_frequency_estimate, # sample_rate)) ### actual estimate bin_f0, B, rsquared, harmonics, limit = get_bin_f0_B( bin_initial_estimate, estimate_B_buffers, noise_cutoff, #estimate_B_buffers, numpy.zeros(defs.LONG_WINDOWSIZE+1), bin_spread_below, bin_spread_above, sample_rate) highest_harmonic = 0 for h in harmonics: if highest_harmonic < h.n: highest_harmonic = h.n limit = min(limit, highest_harmonic) # HACK: remove limit #limit = defs.TOTAL_HARMONICS #print "limit to:", limit #harmonics_enable = [True]*defs.TOTAL_HARMONICS harmonics_enable = [True] * limit bins_estimate = [ partials.mode_B2freq(bin_f0, i, B) for i in range(1, len(harmonics_enable) + 1) ] bins_naive = [i * bin_f0 for i in range(1, len(harmonics_enable) + 1)] if defs.B_PLOT: pylab.figure() pylab.plot(initial_noise_freqs, stft.amplitude2db(initial_noise_floor), color='black') #pylab.plot(initial_noise_freqs, # stft.amplitude2db(initial_noise_floor)+defs.B_MINIMUM_HARMONIC_SNR, # color='black') pylab.xlabel("Frequency (seconds)") pylab.ylabel("Power (/ dB)") for i in range(estimate_B_buffers.shape[0]): #color = matplotlib.cm.spring(float(wav_i)/len(filenames)) #color = matplotlib.cm.RdYlGn( #color = matplotlib.cm.spring( # float(i)/len(estimate_B_buffers_this_list)) pylab.plot( freqs, stft.amplitude2db(estimate_B_buffers[i, :]), #color=color, color="orange", alpha=0.5, label=basename, ) for est in bins_estimate: low = stft.bin2hertz(est - bin_spread_below, sample_rate) high = stft.bin2hertz(est + bin_spread_above, sample_rate) if True: pylab.axvspan(low, high, color='c', alpha=0.3) else: pylab.axvline( stft.bin2hertz(est, sample_rate), color='cyan', alpha=0.3, #linewidth=2.0 ) for naive in bins_naive: freq = stft.bin2hertz(naive, sample_rate) pylab.axvline( freq, color='grey', alpha=0.2, #linewidth=2.0 ) for j, harm in enumerate(harmonics): if harm.mag == 0: continue fn = stft.bin2hertz(harm.fft_bin, sample_rate) mag = stft.amplitude2db(harm.mag) #pylab.plot(fn, mag, 'o', # color='green' # ) pylab.xlabel("Frequency") pylab.ylabel("Decibels") if defs.B_DUMP_HARMS: t_fns = [] t_mags = [] for j, harm in enumerate(harmonics): if harm.mag == 0: continue fn = stft.bin2hertz(harm.fft_bin, sample_rate) mag = stft.amplitude2db(harm.mag) t_fns.append(fn) t_mags.append(mag) data = numpy.vstack((t_fns, t_mags)).transpose() numpy.savetxt("B-harms.txt", data) if defs.B_PLOT: pylab.show() f0 = stft.bin2hertz(bin_f0, sample_rate) stiff_ideal_limit = stiff_ideal_conflict.find_limit( bin_f0, B, bin_spread_below, bin_spread_above) lim = min(stiff_ideal_limit, limit) detected_freqs = StringFreqsB(f0, B, lim) stats = StringFreqsB_stats() stats.num_files = len(filenames) stats.rsquared = rsquared stats.highest_mode_detected = limit stats.highest_mode_stiff_ideal = stiff_ideal_limit stats.basename = basename adjusted_B, delta_fn = adjust_B.adjust(basename, limit, f0, B) if adjusted_B is not None: stiff_ideal_lim_adjusted = stiff_ideal_conflict.find_limit( bin_f0, adjusted_B, bin_spread_below, bin_spread_above) lim = min(stiff_ideal_lim_adjusted, limit) adjusted_freqs = StringFreqsB(f0, adjusted_B, lim) adjusted_freqs.delta_fn = delta_fn stats.highest_mode_stiff_ideal_adjusted = stiff_ideal_lim_adjusted stats.delta_fn = delta_fn final = StringFreqsB( f0, adjusted_B, min(stats.highest_mode_detected, stats.highest_mode_stiff_ideal, stiff_ideal_lim_adjusted)) else: adjusted_freqs = None final = StringFreqsB( f0, B, min(stats.highest_mode_detected, stats.highest_mode_stiff_ideal)) return detected_freqs, adjusted_freqs, stats, final
pl.legend() result = [] for i, tmp in enumerate(xs): pl.subplot(520 + 3 + i * 2) pl.plot(tmp, label="分段%s" % (i + 1)) pl.gca().set_yticklabels([]) pl.gca().set_xticklabels([]) pl.legend() pl.subplot(520 + 3 + i * 2 + 1) tmp = np.convolve(tmp, h) result.append(tmp) pl.plot(tmp, label="分段卷积%s" % (i + 1)) pl.gca().set_yticklabels([]) pl.gca().set_xticklabels([]) pl.axvspan(i * 100, i * 100 + 200, alpha=0.3, facecolor="g") pl.legend() pl.subplot(529) pl.plot(np.convolve(x, h), label="原始信号卷积") pl.gca().set_yticklabels([]) pl.gca().set_xticklabels([]) pl.legend() pl.subplot(5, 2, 10) pl.plot(np.sum(result, axis=0), label="分段卷积和") pl.gca().set_yticklabels([]) pl.gca().set_xticklabels([]) pl.legend() pl.subplots_adjust(hspace=0.05,
def cornerplot(model1, model2, show_cuts=False): plt.switch_backend("pdf") plt.style.use("y1a1") matplotlib.rcParams["ytick.minor.visible"]=False matplotlib.rcParams["xtick.minor.visible"]=False matplotlib.rcParams["ytick.minor.width"]=0.1 matplotlib.rcParams["ytick.major.size"]=2.5 matplotlib.rcParams["xtick.major.size"]=2.5 matplotlib.rcParams["xtick.minor.size"]=1.8 ni,nj=4,4 #ni,nj=np.genfromtxt("%s/shear_xi_plus/values.txt"%theory1[0]).T[2] ni = int(ni) nj = int(nj) #if data is not None: # data = fi.FITS(data) rows, cols = ni+1, nj+2 count = 0 for i in range(ni): for j in range(nj): count+=1 if j>i: continue print(i,j) #(xp,xip,dxip),(xm,xim,dxim) = get_real_spectra(i,j,data,error=True) posp = positions[(i+1,j+1,"+")] ax = plt.subplot(rows,cols,posp) ax.annotate("(%d, %d)"%(i+1,j+1), (3.,(yticks[0]+yticks[1])/2), textcoords='data', fontsize=9, ) ax.yaxis.set_tick_params(which='minor', left='off', right='off') plt.ylim(ymin,ymax) #plt.yscale("log") plt.xscale("log") if (posp==19) or (posp==1) or (posp==7) or (posp==13): plt.yticks(visible=True) plt.yticks(yticks[:-1],fontsize=ytickfontsize) else: plt.yticks(visible=False) if (posp==19): plt.ylabel(r"$\theta \xi_+ \times 10^{4}$", fontsize=11) plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$", fontsize=10) else: pass if posp in [19,14,9,4]: plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$ ", fontsize=10) plt.xlim(2.2,270) plt.xticks([10,100],["10", "100"], fontsize=9) #plt.yticks([-2,0,2,4,6,8],['-2', '0', '2', '4', '6', '8']) plt.axhline(0, color='k', ls=':') if show_cuts: xlower,xupper = lims['+'][(i+1,j+1)] plt.axvspan(1e-6, xlower, color='gray',alpha=0.2) plt.axvspan(xupper, 500, color='gray',alpha=0.2) linestyles=['-',':','--','-'] xta,xip_theory_a,xim_theory_a, xip_theory_gi_a,xim_theory_gi_a, xip_theory_ii_a,xim_theory_ii_a = get_theory_spectra(i,j,model1) xtb,xip_theory_b,xim_theory_b, xip_theory_gi_b,xim_theory_gi_b, xip_theory_ii_b,xim_theory_ii_b = get_theory_spectra(i,j,model2) # import pdb ; pdb.set_trace() # xip_a_remapped = (interp_xip_a(np.log10(xip_a[0]))) # xip_b_remapped = (interp_xip_b(np.log10(xip_b[0]))) #plt.errorbar(xp, xp*xip*1e4, yerr=xp*dxip*1e4, marker='.', linestyle='none', markerfacecolor='k', markeredgecolor='k', ecolor='k',markersize=markersize) # p1 = plt.plot(xta,xta*xip_theory*1e4,color='darkmagenta',lw=1.5, label='GG+GI+II') # plt.plot(xta,F*xta*(xip_theory_gi+xip_theory_ii)*1e4,color='steelblue',lw=1., ls='-', label='GI') p2 = plt.plot(xta,F*xta*xip_theory_gi_a*1e4,color='plum',lw=1.5, ls='-', label='GI (TATT)') p3 = plt.plot(xta,F*xta*xip_theory_ii_a*1e4,color='midnightblue',lw=1.5, ls='-', label='II (TATT)') p4 = plt.plot(xtb,F*xtb*xip_theory_gi_b*1e4,color='plum',lw=1.5, ls='--', label='GI (NLA)') p5 = plt.plot(xtb,F*xtb*xip_theory_ii_b*1e4,color='midnightblue',lw=1.5, ls='--', label='II (NLA)') #plt.plot(xip_a[0], (xip_b_remapped-xip_a_remapped)/xip_b_remapped, ls=linestyles[iline], color="darkmagenta") # plt.plot(xip_b[0], 1e5*(xip_b[1]-xip_b_remapped), ls=linestyles[iline], color="royalblue") posm = positions[(i+1,j+1,"-")] ax = plt.subplot(rows,cols,posm) ax.annotate("(%d, %d)"%(i+1,j+1), (3,(yticks[0]+yticks[1])/2), textcoords='data', fontsize=9, ) ax.yaxis.set_tick_params(which='minor', left='off', right='off') # ax.xaxis.set_tick_params(which='minor', bottom='on', top='off') plt.ylim(ymin,ymax) ax.yaxis.set_ticks_position("right") ax.yaxis.set_label_position("right") if (posm==30) or (posm==12) or (posm==18) or (posm==24): plt.yticks(visible=True) #plt.ylabel(r"$\Delta \xi_+(\theta)/\xi_+$", fontsize=12) #plt.xlabel(r"$\theta$ / arcmin", fontsize=12) ax.yaxis.set_label_position("right") plt.yticks(yticks,fontsize=ytickfontsize) else: plt.yticks(visible=False) if (posm==30): plt.ylabel(r"$\theta \xi_-\times 10^{4}$", fontsize=11) plt.yticks(yticks[:-1],fontsize=ytickfontsize) else: pass if posm in [30,29,28,27]: plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$ ", fontsize=10) #plt.yscale("log") plt.xscale("log") plt.xlim(2.2,270) # if (posm==27): # plt.xticks([1,10,100],["1","10", "100"], fontsize=9) # else: plt.xticks([10,100],["10", "100"], fontsize=9) #ax.xaxis.grid(True, which='minor') # ax.xaxis.set_minor_locator(MultipleLocator(10)) #plt.yticks([-2,0,2,4,6,8],['-2', '0', '2', '4', '6', '8']) plt.axhline(0, color='k', ls=':') if show_cuts: xlower,xupper = lims['-'][(i+1, j+1)] plt.axvspan(1e-6, xlower, color='gray',alpha=0.2) plt.axvspan(xupper, 500, color='gray',alpha=0.2) #plt.errorbar(xm, xm*xim*1e4, yerr=xm*dxim*1e4, marker='.', linestyle='none', markerfacecolor='k', markeredgecolor='k', ecolor='k',markersize=markersize) p2 = plt.plot(xta,F*xta*xim_theory_gi_a*1e4,color='plum',lw=1.5, ls='-', label='GI (TATT)') p3 = plt.plot(xta,F*xta*xim_theory_ii_a*1e4,color='midnightblue',lw=1.5, ls='-', label='II (TATT)') p4 = plt.plot(xtb,F*xtb*xim_theory_gi_b*1e4,color='plum',lw=1.5, ls='--', label='GI (NLA)') p5 = plt.plot(xtb,F*xtb*xim_theory_ii_b*1e4,color='midnightblue',lw=1.5, ls='--', label='II (NLA)') #plt.plot(xim_a[0], 1e5*(xim_a[1]-xim_a_remapped), ls=linestyles[iline], color="red") #plt.plot(xim_b[0], 1e5*(xim_b[1]-xim_b_remapped), ls=linestyles[iline], color="royalblue") # plt.plot(xip_a[0], (xim_b_remapped-xim_a_remapped)/xim_b_remapped, ls=linestyles[iline], color="darkmagenta") plt.legend([p2,p3,p4,p5],title='title', bbox_to_anchor=(1.05, 1), loc='upper right', fontsize=12) # ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width*0.65, box.height]) legend_x = 4.2 legend_y = 5.2 proxies = [plt.Line2D([0,2.5], [0,0], linestyle=ls, linewidth=1.5, color=lc) for ls,lc in [('-','plum'),('-','midnightblue'),('--','plum'),(':','midnightblue')]] plt.legend(proxies,['GI (TATT)', 'II (TATT)', 'GI (NLA)', 'II (NLA)'], loc='upper right', bbox_to_anchor=(legend_x, legend_y), fontsize=9) plt.subplots_adjust(hspace=0,wspace=0, bottom=0.14,left=0.14, right=0.88) plt.savefig("plots/theory_ias_datavector_xipm_maglim.pdf") plt.savefig("plots/theory_ias_datavector_xipm_maglim.png")
def _lss_corr(obs, interactive=True, maxcr=False, figno=20, rawxy=None, target='target', chatter=0): '''determine the LSS correction for the readout streak source ''' import os import numpy as np try: from astropy.io import fits except: import pyfits as fits from pylab import figure,imshow,ginput,axvspan,\ axhspan,plot,autumn,title,clf file = obs['infile'] ext = obs['extension'] cols = obs['streak_col_SN_CR_ERR'] kol = [] countrates = [] circle = [ np.sin(np.arange(0, 2 * np.pi, 0.05)), np.cos(np.arange(0, 2 * np.pi, 0.05)) ] for k in cols: kol.append(k[1]) # S/N countrates.append(k[2]) kol = np.array(kol) if len(kol) == 0: print("zero array kol in _lss_corr ???!!!!") print("LSS correction cannot be determined.") return 1.0, (0, 0), (1100.5, 1100.5) k_sn_max = np.where(np.max(kol) == kol) # maximum s/n column print("k S/N max=", k_sn_max[0][0]) kol = [] for k in cols: kol.append(k[0]) # column number relative to bottom rh corner subimage if len(kol) == 0: print("LSS correction cannot be determined.") return 1.0, (0, 0), (1100.5, 1100.5) im = fits.getdata(file, ext=ext) hdr = fits.getheader(file, ext=ext) #binx = hdr['binx'] mn = im.mean() sig = im.std() # plot figure(figno) clf() autumn() imshow(im, vmin=mn - 0.2 * sig, vmax=mn + 2 * sig) if rawxy != None: rawx, rawy = rawxy R = hdr['windowdx'] / 15. plot(R * circle[0] + rawx - hdr['windowy0'], R * circle[1] + rawy - hdr['windowx0'], '-', color='m', alpha=0.7, lw=2) title(u"PUT CURSOR on your OBJECT", fontsize=16) if not maxcr: count = 0 for k in kol: axvspan(k - 6, k + 6, 0.01, 0.99, facecolor='k', alpha=0.3 - 0.02 * count) count += 1 else: k = k_sn_max[0][0] axvspan(k - 10, k + 10, 0.01, 0.99, facecolor='k', alpha=0.2) happy = False skip = False count = 0 while not happy: print("put the cursor on the location of your source") count += 1 coord = ginput(timeout=0) print("selected:", coord) if len(coord[0]) == 2: print("window corner:", hdr['windowx0'], hdr['windowy0']) xloc = coord[0][0] + hdr['windowx0'] yloc = coord[0][1] + hdr['windowy0'] print("on detector (full raw image) should be :", xloc, yloc) #plot(coord[0][0],coord[0][1],'+',markersize=14,color='k',lw=2) #can't see it axhspan(coord[0][1] - 6, coord[0][1] + 6, 0, 1, facecolor='k', alpha=0.3) if rawxy != None: rawx, rawy = rawxy R = hdr['windowdx'] / 15. plot(R * circle[0] + rawx - hdr['windowx0'], R * circle[1] + rawy - hdr['windowy0'], '-', color='k', alpha=0.7, lw=1) #plot(rawx-hdr['windowx0'],rawy-hdr['windowy0'],'o',markersize=25,color='w',alpha=0.3) ans = raw_input("happy (yes,skip,no): ") if len(ans) > 0: if ans.upper()[0] == 'Y': happy = True if ans.upper()[0] == 'S': return 0.0, coord[0], (yloc + 104, xloc + 78) else: print("no position found") if count > 10: print("Too many tries: aborting") happy = True im = '' try: lss = 1.0 band = obs['band'] caldb = os.getenv('CALDB') command = "quzcif swift uvota - "+band.upper()+\ " SKYFLAT "+\ obs['dateobs'].split('T')[0]+" "+\ obs['dateobs'].split('T')[1]+" - > lssfile.1234.tmp" print(command) os.system(command) f = open('lssfile.1234.tmp') lssfile = f.readline() f.close() f = fits.getdata(lssfile.split()[0], ext=int(lssfile.split()[1])) lss = f[yloc, xloc] print("lss correction = ", lss, " coords=", coord[0], (yloc + 104, xloc + 78)) return lss, coord[0], (yloc + 104, xloc + 78) except: print("LSS correction cannot be determined.") return 1.0, (0, 0), (1100.5, 1100.5)
print "Expt %s, Mnu=0.1, sigma(Mnu)/Mnu = %3.4f" % ( name[j], sigmas[-1] / mnu_vals[i]) P.show() exit() P.xlabel("$z$", fontdict={'fontsize': '20'}) P.ylabel("Fractional error", fontdict={'fontsize': '20'}) P.ylim((0., 0.16)) P.xlim((0., 2.01)) # Legend P.legend(loc='upper left', prop={'size': 'x-large'}, ncol=2) # Shaded regions in different redshift regimes P.axvspan(np.max(zclist[0]), 3., ec='none', fc='#f2f2f2') P.axvspan(0., np.min([np.min(_zc) for _zc in zclist]), ec='none', fc='#cdcdcd') P.axvspan(np.min([np.min(_zc) for _zc in zclist]), np.min(zclist[4]), ec='none', fc='#f2f2f2') # Display options fontsize = 18. for tick in P.gca().yaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) for tick in P.gca().xaxis.get_major_ticks(): tick.label1.set_fontsize(fontsize) P.tight_layout() P.show()
X, dX, colour = inputs[label] if colour == '#000000': c = 'darkmagenta' else: c = colour plt.errorbar([X], [y], xerr=dX, marker='*', markeredgecolor=c, markerfacecolor=c, ecolor=c, linestyle='none') if i == 0: plt.axvspan(X - dX, X + dX, color='plum', alpha=0.2) plt.axvline(X, color='k', ls=':') if label == r'$9.$ Planck 18 TT+TE+EE': plt.axhline(y + (dy / 2), color='k', ls='--') plt.annotate(label, xy=(0.415, y - (dy / 8)), fontsize=fontsize, color=colour) print(label) y -= dy plt.subplots_adjust(wspace=0, hspace=0,
def locus2hydrophobicity_plot(biodb, locus): import pylab import manipulate_biosqldb server, db = manipulate_biosqldb.load_db(biodb) # Kyte & Doolittle index of hydrophobicity kd = { 'A': 1.8, 'R': -4.5, 'N': -3.5, 'D': -3.5, 'C': 2.5, 'Q': -3.5, 'E': -3.5, 'G': -0.4, 'H': -3.2, 'I': 4.5, 'L': 3.8, 'K': -3.9, 'M': 1.9, 'F': 2.8, 'P': -1.6, 'S': -0.8, 'T': -0.7, 'W': -0.9, 'Y': -1.3, 'V': 4.2 } sql = 'select locus_tag, translation from orthology_detail_%s where locus_tag="%s"' % ( biodb, locus) data = server.adaptor.execute_and_fetchall(sql, )[0] locus = data[0] seq = data[1] num_residues = len(seq) #print matplotlib.get_cachedir() values = [] for residue in seq: values.append(kd[residue]) # I've computed the values for each residue. Now compute the moving # average for a window size of 19. Transmembrane helixes are often # about 20 residues in length so peaks in this plot suggest # transmembrane regions. window_size = 19 half_window = int(round((window_size - 1) / 2, 0)) # Precompute the offsets list for better performance. offsets = range(-half_window, half_window + 1) y_data = [] for i in range(half_window, num_residues - half_window): average_value = 0.0 for offset in offsets: average_value += values[i + offset] y_data.append(average_value / window_size) # Exclude the first and last residues. # The final list is in biologist coordinates (the first residue is # index 1) x_data = range(half_window, half_window + len(y_data)) fig, ax = pylab.subplots(nrows=1, ncols=1, figsize=(10, 5)) ax.plot(x_data, y_data, linewidth=1.0) # Draw a reasonable cutoff for membrane prediction # Value of 1.6 taken from # http://arbl.cvmbs.colostate.edu/molkit/hydropathy/ #pylab.axhline(y=1.6) # Draw the known helix and ribbon ranges sql2 = 'select start, stop from interpro_%s where locus_tag="%s" and signature_accession="TRANSMEMBRANE"' % ( biodb, locus) transmembrane_data = server.adaptor.execute_and_fetchall(sql2, ) for transmembrane in transmembrane_data: pylab.axvspan(transmembrane[0], transmembrane[1], facecolor="yellow", alpha=0.4) # helix # Show exactly the length of the sequence pylab.axis(xmin=1, xmax=num_residues) pylab.xlabel("residue number") pylab.ylabel("hydrophobicity (moving average over %d values)" % window_size) record_id = '%s' % locus pylab.title("K&D hydrophobicity for " + record_id) return fig # save the figure to file
def make_norm_dist(x, mean, sd): return 1.0/(sd*np.sqrt(2*np.pi))*np.exp(-(x - mean)**2/(2*sd**2)) x = np.linspace(10, 110, 1000) green = make_norm_dist(x, 50, 10) pink = make_norm_dist(x, 60, 10) blue = green + pink # create a spline of x and blue-np.max(blue)/2 spline = UnivariateSpline(x, blue-np.max(blue)/2, s=0) r1, r2 = spline.roots() # find the roots pl.plot(x, blue) pl.axvspan(r1, r2, facecolor='g', alpha=0.5) pl.show() def FWHM(X,Y): half_max = max(Y) / 2. #find when function crosses line half_max (when sign of diff flips) #take the 'derivative' of signum(half_max - Y[]) d = sign(half_max - array(Y[0:-1])) - sign(half_max - array(Y[1:])) #plot(X[0:len(d)],d) #if you are interested #find the left and right most indexes left_idx = find(d > 0)[0] right_idx = find(d < 0)[-1]
moments = io.readBinaryFile(moment_files[file_number]) moments = moments[0].reshape(N_q2, N_q1, 3) density = moments[:, :, 0] density = density - density_bg moments = io.readBinaryFile(moment_files_2[file_number]) moments = moments[0].reshape(N_q2, N_q1, 3) density_2 = moments[:, :, 0] density_2 = density_2 - density_bg pl.plot(q1, np.abs(density[0, :]), color='C0') pl.plot(q1, np.abs(density_2[0, :]), color='C1') pl.ylim(ymax=50) pl.axvline(4.85, color='k', ls='--') pl.axvline(3.85, color='k', ls='--') #pl.axvline(0.5, color = 'k', ls = '--') #pl.axvline(4.5, color = 'k', ls = '--') pl.axvspan(4.8, 4.9, color='k', alpha=0.5) pl.axvspan(0.1, 0.2, color='k', alpha=0.5) pl.xlabel("x ($\mu$m)") #pl.xlabel("y ($\mu$m)") pl.ylabel("n") pl.tight_layout() pl.savefig('images/iv' + '.png') pl.clf()
def ks_test(df, ids): # no need for pairs of ids, i will create them below. ''' Computes KS statistic, returns d-statistic, and pvaue for each pair of individuals. df is a pandas dataframe of the gene expression file ids is a list of all possible pairs of individual names ''' def getMin(x): r=0 x=list(x) m=x[0] #print x #print len(x) for i in range(len(x)): if x[i]<m and x[i+1]>x[i] and abs(m-x[i])>diff: # current D-statistic must be lower than starting D-statistic, next D-statistic must be large than current, current d-statistic must be less than 0.02 lower than starting D-statistic r=readcuts[i] break return r from scipy.stats import ks_2samp import pylab as plt readcuts = np.arange(0,300,2) # make array of cuttoff values result = [] count = 0 for i in ids: stats = [] s1, s2 = i for rc in readcuts: d = filterExprResults(df, rc) x = d[s1] y = d[s2] val = ks_2samp(x, y) # val is D-statistic, and pvalue stats.append(val[0]) # grab only the D-statistic #print s1, s2, str(rc) #print val result.append(stats) count += 1 if count % 100 == 0: print count result = pd.DataFrame(np.array(result).T) result=result.set_index(readcuts) outids = ["|".join(i) for i in ids] result.columns = outids result.to_csv('Dstats%s_%f.txt' % (outext, diff), index=True, header=True, sep='\t') tmins = result.apply(getMin) # sends one columns at a time, one column is one pair of samples with a D-statistic for each read count cutoff. #print 'These are the cutoff values:' #print (tmins) mean=tmins.mean() median=tmins.median() print 'Mean read cutoff value for all pairs of samples: %d' % (mean) print 'Median read cutoff value for all pairs of samples: %d' % (median) tmins.to_csv('AllMeanReadCutoffValues%s_%f.txt' % (outext, diff), index=True, header=True, sep='\t') std=tmins.std() result.plot(lw=0.5,colormap='Set1',legend=False) plt.axvspan(mean-std/2,mean+std/2,color='g',alpha=0.3) plt.xlabel('read count threshold') plt.ylabel('KS') plt.savefig('KS_test.AllSamples%s_%f.pdf' % (outext, diff)) randcols = result.sample(10, axis=1) randcols.plot(lw=1,colormap='Set1',legend=False) # Make plot readable plt.axvspan(mean-std/2,mean+std/2,color='g',alpha=0.3) plt.xlabel('read count threshold') plt.ylabel('KS') plt.savefig('KS_test.5Samples%s_%f.pdf' % (outext, diff))
if params.x == 'q': pylab.xlabel('Mass ratio used in search') pylab.grid() sort1 = numpy.argsort(x1) sort2 = numpy.argsort(x2) f4 = pylab.axvline(params.exact, linestyle='--', color='r', label="Simulated value") f5 = pylab.axvspan(params.exact - params.space, params.exact + params.space, facecolor='grey', alpha=0.5, label="Template spacing") f3 = pylab.plot(x2[sort2], norm[sort2], '-o', markersize=2, color='k', label="Normalized SNR") pylab.legend([f4, f5], [f4.get_label(), f5.get_label()], loc='upper right') pylab.ylabel('Normalized SNR') ax2 = pylab.twinx()
for i in xrange(n_time_series): # Create new figure fig = pylab.figure() # Plot original data including dating uncertainties ax = fig.add_subplot(len(symbols) + 1, 1, 1) pylab.plot(time[i], values_median[i], "k") pylab.fill_between(time[i], values_left[i], values_right[i], color="0.75") # Plot additional information # Plot RCC episodes for k in xrange(RCC_EPISODES.shape[0]): pylab.axvspan(RCC_EPISODES[k, 0], RCC_EPISODES[k, 1], hatch="/", fill=False, edgecolor="0.5") # Plot Bond events pylab.scatter(BOND_EVENTS, 0.9 * np.ones(len(BOND_EVENTS)) * values_right[i].max(), c='k', marker='*', s=80) pylab.ylabel(DATA_LABEL) pylab.xlim(min_age, max_age) # Add figure label ax.annotate(figure_labels[0], xy=(-0.14, 1.1),
#p.ylabel('Frequency of occurrence', fontsize=FontSize) p.ylabel('number of cells', fontsize=FontSize) p.xticks(size=TickSize) p.yticks(size=TickSize) p.grid(True) #p.figure(2, figsize=(1000,600)) p.subplot(221) p.title(r'$\delta = %(death)1.3f $ $T = %(turb)1.3f $ ' % { "death": death_rate, "turb": tubulence }, fontsize=FontSize + 2) p.plot(x, y, 'ko-', markersize=5, linewidth=2) p.axvspan(repr_mean_number_of_genes - repr_std_number_of_genes, repr_mean_number_of_genes + repr_std_number_of_genes, color=(0.75, 0.75, 0.75, 0.75)) #p.axvspan(real_mean_number_of_genes - real_std_number_of_genes, # real_mean_number_of_genes + real_std_number_of_genes, # color=(0.5,0.5,0.5,0.5), hatch='/') #p.title('Gene number of cells reproducting (solid vertical) and all cells' \ #' (dashed-dotted vertical)') p.hlines(MEAN_diff, 0.0, Gene_max, 'k', linestyles='dashed', lw=3) #p.hlines(real_gene_cost, 0.0, Gene_max, 'k', linestyles='solid') p.vlines(repr_mean_number_of_genes, 0.0, Y_max, 'k', linestyles='solid', lw=2) #p.vlines(real_mean_number_of_genes, 0.0, Y_max , 'k', # linestyles='dashdot', lw=3) p.axis([0.0, Gene_max, 0.0, Y_max]) p.xlabel('number of genes', fontsize=FontSize) p.ylabel('resources', fontsize=FontSize) p.xticks(size=TickSize)
def cornerplot(theory, data, show_cuts=False): plt.switch_backend("pdf") plt.style.use("y1a1") matplotlib.rcParams["ytick.minor.visible"] = False matplotlib.rcParams["xtick.minor.visible"] = False matplotlib.rcParams["ytick.minor.width"] = 0.1 matplotlib.rcParams["ytick.major.size"] = 2.5 matplotlib.rcParams["xtick.major.size"] = 2.5 matplotlib.rcParams["xtick.minor.size"] = 1.8 ni, nj = 4, 4 #ni,nj=np.genfromtxt("%s/shear_xi_plus/values.txt"%theory1[0]).T[2] ni = int(ni) nj = int(nj) if data is not None: data = fi.FITS(data) rows, cols = ni + 1, nj + 2 count = 0 for i in range(ni): for j in range(nj): count += 1 if j > i: continue print(i, j) (xp, xip, dxip), (xm, xim, dxim) = get_real_spectra(i, j, data, error=True) posp = positions[(i + 1, j + 1, "+")] ax = plt.subplot(rows, cols, posp) ax.annotate( "(%d, %d)" % (i + 1, j + 1), (3., yticks[-2]), textcoords='data', fontsize=9, ) ax.yaxis.set_tick_params(which='minor', left='off', right='off') plt.ylim(ymin, ymax) plt.xscale("log") if (posp == 19) or (posp == 1) or (posp == 7) or (posp == 13): #plt.yticks(visible=True) plt.yticks(yticks[:-1], ytick_labels[:-1], fontsize=ytickfontsize, visible=True) else: plt.yticks(visible=False) if (posp == 19): plt.ylabel(r"$\theta \xi_+ \times 10^{4}$", fontsize=11) plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$", fontsize=10) else: pass if posp in [19, 14, 9, 4]: plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$ ", fontsize=10) plt.xlim(2.2, 270) plt.xticks([10, 100], ["10", "100"], fontsize=9) plt.axhline(0, color='k', ls=':') if show_cuts: xlower, xupper = lims['+'][(i + 1, j + 1)] plt.axvspan(1e-6, xlower, color='gray', alpha=0.2) plt.axvspan(xupper, 500, color='gray', alpha=0.2) xlower_opt, xupper_opt = lims_opt['+'][(i + 1, j + 1)] plt.axvspan(1e-6, xlower_opt, color='gray', alpha=0.2) linestyles = ['-', ':', '--', '-'] xta, xip_theory, xim_theory, xip_theory_gi, xim_theory_gi, xip_theory_ii, xim_theory_ii = get_theory_spectra( i, j, theory) plt.errorbar(xp, xp * xip * 1e4, yerr=xp * dxip * 1e4, marker='.', linestyle='none', markerfacecolor='k', markeredgecolor='k', ecolor='k', markersize=markersize) p1 = plt.plot(xta, xta * xip_theory * 1e4, color='#016E51', lw=1.5, label='GG+GI+II') plt.plot(xta, F * xta * (xip_theory_gi + xip_theory_ii) * 1e4, color='#12239E', lw=1., ls='-', label='GI') p2 = plt.plot(xta, F * xta * xip_theory_gi * 1e4, color='#FFA500', lw=1.5, ls='--', label='GI') p3 = plt.plot(xta, F * xta * xip_theory_ii * 1e4, color='#E13102', lw=1.5, ls='-.', label='II') posm = positions[(i + 1, j + 1, "-")] ax = plt.subplot(rows, cols, posm) ax.annotate("(%d, %d)" % (i + 1, j + 1), (3, yticks[-2]), textcoords='data', fontsize=9) ax.yaxis.set_tick_params(which='minor', left='off', right='off') plt.ylim(ymin, ymax) #ax.yaxis.set_ticks_position("right") #ax.yaxis.set_label_position("right") if (posm == 30) or (posm == 12) or (posm == 18) or (posm == 24): #plt.yticks(visible=True) ax.yaxis.set_label_position("right") plt.yticks(yticks, ytick_labels, fontsize=ytickfontsize, visible=True) else: plt.yticks(visible=False) if (posm == 30): plt.ylabel(r"$\theta \xi_-\times 10^{4}$", fontsize=11) ax.yaxis.set_label_position("right") plt.yticks(yticks[:-1], ytick_labels[:-1], fontsize=ytickfontsize) else: pass if posm in [30, 29, 28, 27]: plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$ ", fontsize=10) plt.xscale("log") plt.xlim(2.2, 270) plt.xticks([10, 100], ["10", "100"], fontsize=9) plt.yticks(yticks[:-1], ytick_labels[:-1], fontsize=ytickfontsize) plt.axhline(0, color='k', ls=':') if show_cuts: xlower, xupper = lims['-'][(i + 1, j + 1)] plt.axvspan(1e-6, xlower, color='gray', alpha=0.2) plt.axvspan(xupper, 500, color='gray', alpha=0.2) xlower_opt, xupper_opt = lims_opt['-'][(i + 1, j + 1)] plt.axvspan(1e-6, xlower_opt, color='gray', alpha=0.2) plt.errorbar(xm, xm * xim * 1e4, yerr=xm * dxim * 1e4, marker='.', linestyle='none', markerfacecolor='k', markeredgecolor='k', ecolor='k', markersize=markersize) plt.plot(xta, xta * xim_theory * 1e4, color='#016E51', lw=1.5) plt.plot(xta, F * xta * (xim_theory_gi + xim_theory_ii) * 1e4, color='#12239E', lw=1., ls='-', label='GI') plt.plot(xta, F * xta * xim_theory_gi * 1e4, color='#FFA500', lw=1.5, ls='--') plt.plot(xta, F * xta * xim_theory_ii * 1e4, color='#E13102', lw=1.5, ls='-.') plt.legend([p1, p2, p3], title='title', bbox_to_anchor=(1.05, 1), loc='upper right', fontsize=12) # ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.65, box.height]) legend_x = 4.2 legend_y = 5.2 proxies = [ plt.Line2D([0, 2.5], [0, 0], linestyle=ls, linewidth=1.5, color=lc) for ls, lc in [('-', '#016E51'), ('-', '#12239E'), ('--', '#FFA500'), ('-.', '#E13102')] ] plt.legend(proxies, [ "GG+GI+II", r"$10 \times$ GI+II", r"$10 \times$ GI", r'$10 \times$ II' ], loc='upper right', bbox_to_anchor=(legend_x, legend_y), fontsize=9) plt.subplots_adjust(hspace=0, wspace=0, bottom=0.14, left=0.14, right=0.88) plt.savefig("plots/unblinded_datavector_xipm_maglimbf_final.pdf") plt.savefig("plots/unblinded_datavector_xipm_maglimbf_final.png")
else: trials, _, _, _ = session.get_trials(condition) # if the user has requested a subportion of the session if options.subsession_start > 0.0 or options.subsession_end < 1.0: nt = len(trials) trials = trials[int(nt * options.subsession_start):\ int(nt * options.subsession_end)] spikes = session.get_spike_times(*datum) pl.subplot(subplotsHeight, subplotsWidth, \ subplotsWidth * y + x + 1) physio.plotting.psth.plot(trials, spikes, options.before, \ options.after, options.nbins) pl.axvline(0., color='k') pl.axvspan(0., 0.5, color='k', alpha=0.1) if x == 0: pl.ylabel('Cluster: %i\nRate(Hz)' % datum[1]) else: pl.yticks([]) if y == 0: pl.title('%s' % str(condition), rotation=45) if y < len(data) - 1: pl.xticks([]) else: pl.xticks([0., .5]) pl.xlabel("Seconds") ymaxs[y] = max(ymaxs[y], pl.ylim()[1]) session.close()
def plot_inference_result(y, w1, w2, x1, x2, tau, cell_lines=[], muts=[], title='', figname='test.png'): matplotlib.rcParams.update({'font.size': 12}) fig = PL.figure(figsize=(9, 6)) gs = gridspec.GridSpec(2, 2, width_ratios=[len(w1), len(x1)]) cell_lines = ['LNCaP' if ('LNCaP' in x) else x for x in cell_lines] mut_status = [ '(M)' if mut == "True" else ('' if mut == "False" else '(U)') for mut in muts ] #Signal ax = PL.subplot(gs[0, 0]) im = PL.imshow(y, aspect=1.15, interpolation='none', cmap=PL.get_cmap("coolwarm"), vmin=-3, vmax=3) ax = PL.gca() ax.set_xticks([]) ax.set_yticks(range(len(x1))) ax.set_yticklabels(['gRNA %d' % (grnano + 1) for grnano in range(len(x1))]) if len(cell_lines) > 0: ax.set_xticks(range(len(cell_lines))) ax.set_xticklabels(cell_lines, rotation='vertical') ax.xaxis.tick_top() for t in ax.xaxis.get_ticklines(): t.set_visible(False) for t in ax.yaxis.get_ticklines(): t.set_visible(False) for t, mt in zip(ax.xaxis.get_ticklabels(), mut_status): t.set_fontsize(10) if mt == '(M)': t.set_fontweight('bold') #x PL.subplot(gs[0, 1]) PL.plot([1, 1], [-1, len(x1) + 1], 'k--') PL.plot([0, 0], [-1, len(x1) + 1], 'k--') vdata = [ ST.norm.rvs(x1[i], (x2[i] - x1[i]**2)**0.5, size=5000) for i in range(len(x1)) ] vpos = (SP.arange(len(x1)) + 1)[::-1] clrs = ['#FFFFFF', '#BBCCEE'] for i in range(len(x1)): PL.axhspan(i + 0.5, i + 1.5, facecolor=clrs[i % 2], alpha=0.1) vplot = PL.violinplot(vdata, vpos, widths=0.5 * SP.ones(len(x1)), vert=False, showextrema=True, showmeans=True) for patch, val in zip(vplot['bodies'], x1): col_val = int(0.8 * min(max(256 - val * 128, 0), 255)) patch.set_color('#%02x%02x%02x' % (col_val, col_val, col_val)) vplot['cmeans'].set_color('darkblue') vplot['cmeans'].set_linewidth(2) vplot['cmins'].set_color('#444444') vplot['cmaxes'].set_color('#444444') vplot['cbars'].set_color('#444444') vplot['cbars'].set_visible(False) PL.ylim(0.5, len(x1) + 0.5) PL.xlim(-0.5, 2) ax = PL.gca() PL.xticks([0, 1]) PL.yticks([]) PL.xlabel("gRNA efficacy") PL.title(title) #w PL.subplot(gs[1, 0]) clrs = ['#FFFFFF', '#BBCCEE'] for i in range(len(w1)): PL.axvspan(i - 1, i, facecolor=clrs[i % 2], alpha=0.1) vplot = PL.violinplot([ ST.norm.rvs(w1[i], (w2[i] - w1[i]**2)**0.5, size=5000) for i in range(len(w1)) ], SP.arange(len(w1)) - 0.5, widths=0.9 * SP.ones(len(w1)), showmeans=True, showextrema=True) for patch, val in zip(vplot['bodies'], w1): col_val = int(0.95 * min(max(0, 256 + val * 128), 200)) patch.set_alpha(1.0) clr = im.cmap(im.norm(val)) patch.set_color(clr) vplot['cmeans'].set_color('darkblue') vplot['cmeans'].set_linewidth(2) vplot['cmins'].set_color('#444444') vplot['cmaxes'].set_color('#444444') vplot['cbars'].set_visible(False) PL.plot([-1, len(w1)], [0.0, 0.0], 'k--') PL.xlim(-1, len(w1) - 1) PL.ylim(-3.5, 1) mean_y = np.nanmean(y, axis=0) PL.ylabel("Gene essentiality") PL.xlabel("Cell lines") pws = [ 1.0 - ST.norm.cdf((w1[i]) / np.sqrt(w2[i] - w1[i] * w1[i])) for i in range(len(w1)) ] ax = PL.gca() if len(cell_lines) > 0: ax.set_xticks([]) for t in ax.xaxis.get_ticklines(): t.set_visible(False) PL.subplots_adjust(left=0.08, right=0.94, top=0.82, bottom=0.11, wspace=0.0, hspace=0.0) PL.rcParams['svg.fonttype'] = 'none' PL.savefig(figname, bbox_inches='tight') PL.show(block=False) return fig
def _generate_time_series_plot(self): """ This function generates the actual time series plot""" # This string will show up as text in the plot and looks something # like "Target: 123; Standard:634" samples_per_condition_string = \ "; ".join([("%s: " + str(self.samples_per_condition[label])) % label for label in self.mean_time_series.keys()]) figTS = pylab.figure() # Compute number of rows and cols for subplot-arrangement: # use 8 as upper limit for cols and compute rows accordingly if self.number_of_channels <= 8: nr_of_cols = self.number_of_channels else: nr_of_cols = 8 nr_of_rows = (self.number_of_channels - 1) / 8 + 1 # Set canvas size in inches. These values turned out fine, depending # on [physiological_arrengement] and [shrink_plots] if not self.physiological_arrangement: figTS.set_size_inches((5 * nr_of_cols, 3 * nr_of_rows)) ec_2d = None else: if not self.shrink_plots: figTS.set_size_inches((3 * 11.7, 3 * 8.3)) else: figTS.set_size_inches((4 * 11.7, 4 * 8.3)) ec = self.get_metadata("electrode_coordinates") if ec is None: ec = StreamDataset.ec ec_2d = StreamDataset.project2d(ec) # plot everything channel-wise for i_chan in range(self.number_of_channels): figTS.add_subplot(nr_of_rows, nr_of_cols, i_chan + 1) # actual plotting of the data. This can always be done for tslabel in self.mean_time_series.keys(): tmp_plot = pylab.plot(self.mean_time_series[tslabel][:, i_chan], label=tslabel) cur_color = tmp_plot[0].get_color() if self.error_type != None: for sample in range(self.samples_per_window): current_error = self.error[label][sample, i_chan] pylab.bar( sample - .35, 2 * current_error, width=.7, bottom=self.mean_time_series[tslabel][sample, i_chan] - current_error, color=cur_color, ec=None, alpha=.3) # plotting of features; only if features present if (self.feature_time_series != None): # plot those nice grey circles pylab.plot(self.feature_time_series[:, i_chan], 'o', color='0.5', label='Feature', alpha=0.5) for sample in range(self.samples_per_window): if [sample, i_chan] in self.indexlist: # write down value... pylab.text(sample, self.feature_time_series[sample, i_chan], '%.2f' % self.feature_time_series[sample, i_chan], ha='center', color='black', size='xx-small') # ...compute the corresponding color-representation... marker_color = \ self.own_colormap(self.normalizer(\ self.feature_time_series[sample, i_chan])) # ...and draw vertical boxes at the feature's position pylab.axvspan(sample - .25, sample + .25, color=marker_color, ec=None, alpha=.8) # more format. and rearrangement in case of [phys_arrengement] self._format_subplots('mean time series', i_chan, samples_per_condition_string, ec_2d) # in case of [phys_arrengement], write the figure title only once # and large in the upper left corner of the plot. this fails whenever # there are no more channels in that area, as the plot gets cropped if self.physiological_arrangement: h, l = pylab.gca().get_legend_handles_labels() prop = matplotlib.font_manager.FontProperties(size='xx-large') figTS.legend(h, l, prop=prop, loc=1) if not self.emotiv: text_x = .1 text_y = .92 else: text_x = .4 text_y = .4 if self.shrink_plots: text_y = 1.2 figTS.text(text_x, text_y, 'Channel-wise mean time series\n' + samples_per_condition_string, ha='center', color='black', size=32) return figTS
#Local minima of x=dataset are just the local maxima of -x (minus x) lowest_peaks, _ = find_peaks(-data_fit) ######### showing on plot ################ # plt.plot(data_fit) # plt.plot(lowest_peaks, data_fit[lowest_peaks], ".") # plt.vlines(x=lowest_peaks, ymin=400, ymax=1000, color="#666666", linestyles='dashed') for i in range(0, lowest_peaks.size): plt.axvline(lowest_peaks[i], color="#666666", linestyle='--') isArea = 1 for i in range(1, lowest_peaks.size): if( isArea%2 == 1 ): plt.axvspan(lowest_peaks[i-1], lowest_peaks[i], facecolor="#ECECEC", alpha=0.5) isArea = isArea + 1 # plt.plot(np.zeros_like(x), "--", color="gray") plt.show() #######find minimas, way 2 ##################################### # from scipy.signal import argrelextrema # # argrelextrema() returns array as tuples # #so use only first tuple element at index '0' # #like maximums[0] or minimums[0] # maximums = argrelextrema(data_fit, np.greater) # # print(maximums) # minimums = np.array(argrelextrema(data_fit, np.less))
]) p.xlabel('time passed between reproductions (steps)', fontsize=FontSize) #p.ylabel('Frequency of occurrence', fontsize = FontSize) p.ylabel('number of cells', fontsize=FontSize) p.xticks(size=TickSize) p.yticks(size=TickSize) p.grid(True) p.figure(2, figsize=(12, 6)) p.title('Turbulence level = %(turb)1.3f ; Death rate = %(death)1.3f' % { "turb": tubulence, "death": death_rate }) p.plot(x, y, 'ko-', markersize=4) p.axvspan(repr_mean_number_of_genes - repr_std_number_of_genes, repr_mean_number_of_genes + repr_std_number_of_genes, color=(0.75, 0.75, 0.75, 0.75), hatch='/') p.axvspan(real_mean_number_of_genes - real_std_number_of_genes, real_mean_number_of_genes + real_std_number_of_genes, color=(0.5, 0.5, 0.5, 0.5)) p.title( 'Gene number of cells reproducting (red vertical) and all cells (blue vertical)' ) p.hlines(MEAN_diff, 0.0, N_max, 'g', linestyles='dashed', lw=2) #p.hlines(real_gene_cost, 0.0, N_max, 'k', linestyles='solid') p.vlines(repr_mean_number_of_genes, 0.0, Y_max, 'r', linestyles='dashed', lw=2) p.vlines(real_mean_number_of_genes, 0.0, Y_max, 'b', linestyles='dashed', lw=2) p.axis([0.0, N_max, 0.0, Y_max]) p.xlabel('number of genes', fontsize=FontSize) p.ylabel('resources', fontsize=FontSize) p.xticks(size=TickSize)
# pl.xlim([0,512]) # pl.ylim([300,512]) pl.axis('off') counter+=1 # pl.title(fl.split('/')[-2][:8]) #%% pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxCSUSCR']],0)) pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxCSUSNOCR']],0)) pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxCSCR']],0)) pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxCSNOCR']],0)) pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idx_US']],0)) pl.legend(['idxCSUSCR','idxCSUSNOCR','idxCSCR','idxCSNOCR','idxUS']) pl.xlabel('time to US (s)') pl.ylabel('eyelid closure') pl.axvspan(-ISI,ISI, color='g', alpha=0.2, lw=0) pl.axvspan(0,0.03, color='r', alpha=0.2, lw=0) pl.xlim([-.5, .5]) pl.ylim([-.1, None]) #%% pl.close() pl.subplot(2,2,1) pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxCR']],0),'-*') pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxNOCR']],0),'-d') pl.plot(time_e_mat,np.mean(eye_mat[triggers_out['nm_idxUS']],0),'-o') pl.xlabel('Time to US (s)') pl.ylabel('Eyelid closure') pl.axvspan(-ISI,ISI, color='g', alpha=0.2, lw=0) pl.axvspan(0,0.03, color='r', alpha=0.2, lw=0)
#i=0 #while i<10000000000: # if i % 100 == 0: # print i # subprocess.call(["free","-m"]) # tmp = np.random.random((50,460,10)) # tmp2 = mpm.forward(tmp) # i+=1 #assert 1==0 #fs, signif_cluster_times, signif_cluster_probs, cluster_times, cluster_probs = cs.search() ##Plotting for a better understanding import pylab as p p.subplot(211) p.plot(condition1.mean(axis=1), label="Condition 1") p.plot(condition2.mean(axis=1), label="Condition 2") p.ylabel("signal [a.u.]") p.subplot(212) #for i_c in range(len(cluster_times)): # start, end = cluster_times[i_c] # p.axvspan(start,end,color="b",alpha=0.3) # p.text(start,2,"%.2f"%cluster_probs[i_c],fontsize=8) signif_cluster_times = [cl[2] for cl in cm.clusters] for i_c in range(len(signif_cluster_times)): start, end = signif_cluster_times[i_c] p.axvspan(start, end, 0.95, 1.0, color="b", alpha=1.0) #p.plot(fs) p.xlabel("timepoints") p.ylabel("f-values") p.show()
z2_avg_chunk2 += z2_list[j - width * interval:j + width * len(chunk1) + interval * width] z1_avg_chunk1 /= len(chunk1test_start[1:-5]) z2_avg_chunk1 /= len(chunk1test_start[1:-5]) z1_avg_chunk2 /= len(chunk2test_start[1:-5]) z2_avg_chunk2 /= len(chunk2test_start[1:-5]) avg_chunk_range = np.zeros(width * (len(chunk1) + interval * 4)) - 1 avg_chunk_range[interval * width:width * len(chunk1) + interval * width] = 1 fig = plt.figure(figsize=(7, 2)) ax = plt.subplot(1, 1, 1) pl.plot(z1_list, lw=2.5, c='orangered') pl.plot(z2_list, lw=2.5, c='dodgerblue') for i in (chunk1test_start): pl.axvspan(i, i + width * len(chunk1), facecolor='dodgerblue', alpha=0.3,linewidth=0) for i in (chunk2test_start): pl.axvspan(i, i + width * len(chunk2), facecolor='orangered', alpha=0.3,linewidth=0) pl.ylim(min(np.min(z1_list[0:test_len]), np.min(z2_list[0:test_len])) - 0.1, max(np.max(z1_list[0:test_len]), np.max(z2_list[0:test_len])) + 0.1) plot_start = 0 pl.xlim(plot_start, plot_start + 6000) plt.xlabel("Time [ms]", fontsize=15) plt.ylabel("Activity", fontsize=15) fig.subplots_adjust(bottom=0.25, left=0.15) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left')
f_list[:, i] = f nspk_random, tspk_random = pl.nonzero(random_mat == 1) nspk1, tspk1 = pl.nonzero(pat1_mat == 1) nspk2, tspk2 = pl.nonzero(pat2_mat == 1) nspk3, tspk3 = pl.nonzero(pat3_mat == 1) fig = plt.figure(figsize=(7, 2)) ax = plt.subplot(1, 1, 1) for i in range(N): pl.plot(f_list[i, :], lw=1.5, c='k') for i in (pat1_start): pl.axvspan(i, i + width, facecolor='orangered', alpha=0.3, linewidth=0) for i in (pat2_start): pl.axvspan(i, i + width, facecolor='dodgerblue', alpha=0.3, linewidth=0) for i in (pat3_start): pl.axvspan(i, i + width, facecolor='limegreen', alpha=0.3, linewidth=0) pl.xlim([0, 1400]) pl.ylim([-0.1, 1.1]) plt.xlabel("Time [ms]", fontsize=11) plt.ylabel("Activity", fontsize=11) fig.subplots_adjust(bottom=0.25, left=0.1) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left')
def plot_histograms(self, start_day=None, end_day=None, bins=None, width=0.8, fig_args=None, font_size=18): ''' Plots a histogram of the number of transmissions. Args: start_day (int/str): the day on which to start counting people who got infected end_day (int/str): the day on which to stop counting people who got infected bins (list): bin edges to use for the histogram width (float): width of bars fig_args (dict): passed to pl.figure() font_size (float): size of font ''' # Process targets n_targets = self.count_targets(start_day, end_day) # Handle bins if bins is None: max_infections = n_targets.max() bins = np.arange(0, max_infections+2) # Analysis counts = np.histogram(n_targets, bins)[0] bins = bins[:-1] # Remove last bin since it's an edge total_counts = counts*bins n_bins = len(bins) index = np.linspace(0, 100, len(n_targets)) sorted_arr = np.sort(n_targets) sorted_sum = np.cumsum(sorted_arr) sorted_sum = sorted_sum/sorted_sum.max()*100 change_inds = sc.findinds(np.diff(sorted_arr) != 0) max_labels = 15 # Maximum number of ticks and legend entries to plot # Plotting fig_args = sc.mergedicts(dict(figsize=(24,15)), fig_args) pl.rcParams['font.size'] = font_size fig = pl.figure(**fig_args) pl.set_cmap('Spectral') pl.subplots_adjust(left=0.08, right=0.92, bottom=0.08, top=0.92) colors = sc.vectocolor(n_bins) pl.subplot(1,2,1) w05 = width*0.5 w025 = w05*0.5 pl.bar(bins-w025, counts, width=w05, facecolor='k', label='Number of events') for i in range(n_bins): label = 'Number of transmissions (events × transmissions per event)' if i==0 else None pl.bar(bins[i]+w025, total_counts[i], width=w05, facecolor=colors[i], label=label) pl.xlabel('Number of transmissions per person') pl.ylabel('Count') if n_bins<max_labels: pl.xticks(ticks=bins) pl.legend() pl.title('Numbers of events and transmissions') pl.subplot(2,2,2) total = 0 for i in range(n_bins): pl.bar(bins[i:], total_counts[i], width=width, bottom=total, facecolor=colors[i]) total += total_counts[i] if n_bins<max_labels: pl.xticks(ticks=bins) pl.xlabel('Number of transmissions per person') pl.ylabel('Number of infections caused') pl.title('Number of transmissions, by transmissions per person') pl.subplot(2,2,4) pl.plot(index, sorted_sum, lw=3, c='k', alpha=0.5) n_change_inds = len(change_inds) label_inds = np.linspace(0, n_change_inds, max_labels).round() # Don't allow more than this many labels for i in range(n_change_inds): if i in label_inds: # Don't plot more than this many labels label = f'Transmitted to {bins[i+1]:n} people' else: label = None pl.scatter([index[change_inds[i]]], [sorted_sum[change_inds[i]]], s=150, zorder=10, c=[colors[i]], label=label) pl.xlabel('Proportion of population, ordered by the number of people they infected (%)') pl.ylabel('Proportion of infections caused (%)') pl.legend() pl.ylim([0, 100]) pl.grid(True) pl.title('Proportion of transmissions, by proportion of population') pl.axes([0.30, 0.65, 0.15, 0.2]) berry = [0.8, 0.1, 0.2] dirty_snow = [0.9, 0.9, 0.9] start_day = self.day(start_day, which='start') end_day = self.day(end_day, which='end') pl.axvspan(start_day, end_day, facecolor=dirty_snow) pl.plot(self.sim_results['t'], self.sim_results['cum_infections'], lw=2, c=berry) pl.xlabel('Day') pl.ylabel('Cumulative infections') return fig
pk_rW = resW['pk'] pk_r = n.abs(res['pk']) err_d = dirty['err'] err_r = res['err'] err_rW = resW['err'] fig = pl.figure() ax = fig.add_subplot(211) tau_h = 100 + 15. #in ns k_h = C.pspec.dk_deta(C.pspec.f2z(dirty['freq'])) * tau_h pl.vlines(k_h, -1e7, 1e13, linestyles='--', linewidth=1.5) #pl.vlines(-k_h, -1e7, 1e13, linestyles='--', linewidth=1.5) pl.axvspan(-k_h, k_h, color='red', alpha=0.5) ax.set_yscale("log", nonposx='noclip') ax.errorbar(k_d, n.abs(pk_d) / pk_d, yerr=err_d / pk_d, fmt='ko') ax.errorbar(k_rW, n.abs(pk_rW) / pk_d, yerr=err_rW / pk_d, fmt='r.') ax.errorbar(k_r, n.abs(pk_r) / pk_d, yerr=err_r / pk_d, fmt='b.') ax.set_ylim( n.min(n.append(pk_d, pk_r)) + err_r.min(), n.max(n.append(pk_r, pk_d)) + err_d.max()) ax.set_xticklabels([]) pl.xlabel(r'$k_\parallel\ [h\ {\rm Mpc}^{-1}]$', fontsize='large') pl.ylabel(r'$P(k)[\ {\rm mK}^2\ (h^{-1}\ {\rm Mpc})^3]$', fontsize='large') pl.title('z = ' + str(round(1.42 / dirty['freq'] - 1, 2))) #tau_h = 100 + 15. #in ns
count += stp finl = count count = x[0] for i in B: if i < 0.999: break count += stp init = count time = (finl - init) * 0.1 / 1000 plt.figure(figsize=(18, 6), dpi=100) plt.rc('xtick', labelsize=15) plt.rc('ytick', labelsize=15) plt.plot(x, A, 'r', label=r"$hcp$", linewidth=1.5) plt.plot(x, B, 'b', label=r"$fcc$", linewidth=1.5) plt.xlabel('0.1 fs for every step', fontsize=28) plt.ylabel('Structure Similarity', fontsize=28) p = plt.axvspan(init, finl, facecolor='g', alpha=0.5) plt.text(55000, 0.91, r'$time \ =\ $' + str(time) + r'$\ ps$', color='k', fontsize=18) #plt.grid(True) plt.legend(numpoints=15, prop={'size': 28}, loc="lower right", frameon=False) plt.savefig("Structure-similarity.png")
# Let's see when the detector was active. # Note that all units are in seconds and that the + from pycbc import dq import pylab start_time = 1126051217 end_time = start_time + 10000000 # Get times that the Livingston detecot has CBC injections into the data segs = dq.query_flag('L1', 'CBC_HW_INJ', start_time, end_time) pylab.figure(figsize=[10, 2]) for seg in segs: start, end = seg pylab.axvspan(start, end, color='blue') pylab.xlabel('Time (s)') pylab.show()
def cornerplot(theory, theory2, show_cuts=False): plt.switch_backend("pdf") plt.style.use("y1a1") matplotlib.rcParams["ytick.minor.visible"] = False matplotlib.rcParams["xtick.minor.visible"] = False matplotlib.rcParams["ytick.minor.width"] = 0.1 matplotlib.rcParams["ytick.major.size"] = 2.5 matplotlib.rcParams["xtick.major.size"] = 2.5 matplotlib.rcParams["xtick.minor.size"] = 1.8 ni, nj = 4, 4 #ni,nj=np.genfromtxt("%s/shear_xi_plus/values.txt"%theory1[0]).T[2] ni = int(ni) nj = int(nj) rows, cols = ni + 1, nj + 2 count = 0 for i in range(ni): for j in range(nj): count += 1 if j > i: continue print(i, j) # (xp,xip,dxip),(xm,xim,dxim) = get_real_spectra(i,j,data,error=True) posp = positions[(i + 1, j + 1, "+")] ax = plt.subplot(rows, cols, posp) ax.annotate( "(%d, %d)" % (i + 1, j + 1), (3., 2), textcoords='data', fontsize=9, ) ax.yaxis.set_tick_params(which='minor', left='off', right='off') plt.ylim(-6, 4) plt.xscale("log") if (posp == 19) or (posp == 1) or (posp == 7) or (posp == 13): plt.yticks(visible=True) #plt.ylabel(r"$\Delta \xi_+(\theta)/\xi_+$", fontsize=12) #plt.xlabel(r"$\theta$ / arcmin", fontsize=12) plt.yticks([-6, -4, -2, 0, 2], fontsize=ytickfontsize) else: plt.yticks(visible=False) if (posp == 19): plt.ylabel( r"$ \Delta \xi_+/\xi_+ = \xi^{\rm TATT}_+ - \xi^{\rm NLA}_+/\xi^{\rm NLA}_+ $", fontsize=11) plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$", fontsize=10) #plt.yticks([0,1,2,3],fontsize=ytickfontsize) else: pass if posp in [19, 14, 9, 4]: plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$ ", fontsize=10) plt.xlim(2.2, 270) plt.xticks([10, 100], ["10", "100"], fontsize=9) #plt.yticks([-2,0,2,4,6,8],['-2', '0', '2', '4', '6', '8']) plt.axhline(0, color='k', ls=':') if show_cuts: xlower, xupper = lims['+'][(i + 1, j + 1)] plt.axvspan(1e-6, xlower, color='gray', alpha=0.2) plt.axvspan(xupper, 500, color='gray', alpha=0.2) linestyles = ['-', ':', '--', '-'] xta, xip_theory, xim_theory, xip_theory_gi, xim_theory_gi, xip_theory_ii, xim_theory_ii = get_theory_spectra( i, j, theory) xtb, xip_theory2, xim_theory2, xip_theory2_gi, xim_theory2_gi, xip_theory2_ii, xim_theory2_ii = get_theory_spectra( i, j, theory2) # import pdb ; pdb.set_trace() # xip_a_remapped = (interp_xip_a(np.log10(xip_a[0]))) # xip_b_remapped = (interp_xip_b(np.log10(xip_b[0]))) IA1 = xip_theory_gi + xip_theory_ii IA2 = xip_theory2_gi + xip_theory2_ii plt.plot(xta, (xip_theory - xip_theory2) / xip_theory2, color='darkmagenta', lw=1.5, label='GG+GI+II') plt.plot(xta, (IA1 - IA2) / IA2, color='pink', lw=1.5, ls='-', label='GI') #plt.plot(xip_a[0], (xip_b_remapped-xip_a_remapped)/xip_b_remapped, ls=linestyles[iline], color="darkmagenta") # plt.plot(xip_b[0], 1e5*(xip_b[1]-xip_b_remapped), ls=linestyles[iline], color="royalblue") posm = positions[(i + 1, j + 1, "-")] ax = plt.subplot(rows, cols, posm) ax.annotate( "(%d, %d)" % (i + 1, j + 1), (3, 2), textcoords='data', fontsize=9, ) ax.yaxis.set_tick_params(which='minor', left='off', right='off') # ax.xaxis.set_tick_params(which='minor', bottom='on', top='off') plt.ylim(-6, 4) ax.yaxis.set_ticks_position("right") ax.yaxis.set_label_position("right") if (posm == 30) or (posm == 12) or (posm == 18) or (posm == 24): plt.yticks(visible=True) #plt.ylabel(r"$\Delta \xi_+(\theta)/\xi_+$", fontsize=12) #plt.xlabel(r"$\theta$ / arcmin", fontsize=12) ax.yaxis.set_label_position("right") plt.yticks([-6, -4, -2, 0, 2], fontsize=ytickfontsize) else: plt.yticks(visible=False) if (posm == 30): plt.ylabel(r"$ \Delta \xi_-/ \xi_-$", fontsize=11) plt.yticks([-4, -2, 0, 2], fontsize=ytickfontsize) else: pass if posm in [30, 29, 28, 27]: plt.xlabel(r"$\theta \;\; [ \mathrm{arcmin} ]$ ", fontsize=10) plt.xscale("log") plt.xlim(2.2, 270) # if (posm==27): # plt.xticks([1,10,100],["1","10", "100"], fontsize=9) # else: plt.xticks([10, 100], ["10", "100"], fontsize=9) #ax.xaxis.grid(True, which='minor') # ax.xaxis.set_minor_locator(MultipleLocator(10)) plt.yticks([-4, -2, 0, 2], fontsize=ytickfontsize) plt.axhline(0, color='k', ls=':') if show_cuts: xlower, xupper = lims['-'][(i + 1, j + 1)] plt.axvspan(1e-6, xlower, color='gray', alpha=0.2) plt.axvspan(xupper, 500, color='gray', alpha=0.2) IA1 = xim_theory_gi + xim_theory_ii IA2 = xim_theory2_gi + xim_theory2_ii plt.plot(xta, (xim_theory - xim_theory2) / xim_theory2, color='darkmagenta', lw=1.5, label='GG+GI+II') plt.plot(xta, (IA1 - IA2) / IA2, color='pink', lw=1.5, ls='-', label='GI') #print((IA1-IA2)/IA2) #plt.plot(xim_a[0], 1e5*(xim_a[1]-xim_a_remapped), ls=linestyles[iline], color="red") #plt.plot(xim_b[0], 1e5*(xim_b[1]-xim_b_remapped), ls=linestyles[iline], color="royalblue") # plt.plot(xip_a[0], (xim_b_remapped-xim_a_remapped)/xim_b_remapped, ls=linestyles[iline], color="darkmagenta") # plt.legend([p1,p2,p3],title='title', bbox_to_anchor=(1.05, 1), loc='upper right', fontsize=12) # ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.65, box.height]) legend_x = 4.2 legend_y = 5.2 proxies = [ plt.Line2D([0, 2.5], [0, 0], linestyle=ls, linewidth=1.5, color=lc) for ls, lc in [('-', 'darkmagenta'), ('-', 'pink'), ( '--', 'pink'), (':', 'midnightblue')] ] plt.legend(proxies, ["GG+GI+II", "GI+II"], loc='upper right', bbox_to_anchor=(legend_x, legend_y), fontsize=9) plt.subplots_adjust(hspace=0, wspace=0, bottom=0.14, left=0.14, right=0.88) plt.savefig("plots/unblinded_datavector_xipm_diff.pdf") plt.savefig("plots/unblinded_datavector_xipm_diff.png")
pl.close('all') pl.subplot(211) #pl.title('ROI : ' + label) pl.plot(times*1000, condition1.mean(axis=0),color=color1,linewidth=lWidth,linestyle=lineStyle1) pl.plot(times*1000, condition2.mean(axis=0),color=color2,linewidth=lWidth,linestyle=lineStyle2) pl.ylim([ymin,ymax]) pl.xlabel("time (ms)") #pl.plot(times, condition2.mean(axis=0) - condition1.mean(axis=0), label="ERF Contrast (Event 2 - Event 1)") # pl.ylabel("MEG (T / m)") pl.legend() pl.subplot(212) for i_c, c in enumerate(clusters): c = c[0] if cluster_p_values[i_c] <= 0.05: h = pl.axvspan(times[c.start]*1000, times[c.stop - 1]*1000, color='r', alpha=0.3) print 'sig:', times[c.start], times[c.stop -1], 'p:', cluster_p_values[i_c] else: #pl.axvspan(times[c.start], times[c.stop - 1], color=(0.3, 0.3, 0.3), alpha=0.3) print 'non-sig:', times[c.start], times[c.stop -1], 'p:',cluster_p_values[i_c] hf = pl.plot(times*1000, T_obs, 'g') ymin,ymax = [0, 14] pl.ylim([ymin,ymax]) #pl.legend((h, ), ('cluster p-value < 0.05', )) pl.xlabel("time (ms)") # pl.ylabel("f-values") pl.show()