def show(self): """Displays the graph as a networkkx plot Note: Redraws entire graph each time user moves """ plt.clf() labels = { node_info["node_id"]: room for room, node_info in self.room_map.items() } max_y = max(self.origins.values(), key=lambda node: node.y).y positions = { self.room_map[room]["node_id"]: (origin.x, abs(origin.y - max_y)) for room, origin in self.origins.items() } color_map = ["blue" for _ in labels] color_map[list(labels.values()).index( self._game.player.position["location"])] = "red" minimap = nx.Graph() minimap.add_nodes_from([ node_info["node_id"] for room, node_info in self.room_map.items() ]) minimap.add_edges_from([(node_info["node_id"], e_node) for room, node_info in self.room_map.items() for e_node in node_info["edges"]]) nx.draw(minimap, pos=positions, node_color=color_map, node_size=100) delta = 0.1 pos_higher = {k: (v[0], v[1] + delta) for k, v in positions.items()} nx.draw_networkx_labels(minimap, pos_higher, labels) plt.margins(0.2) plt.show()
def plot_variable_importance(feature_importance, names_cols, save_name, save): """Show Variable importance graph.""" # scale by max importance first 20 variables in column names feature_importance = feature_importance / feature_importance.max() sorted_idx = np.argsort(feature_importance)[::-1][:20] barPos = np.arange(sorted_idx.shape[0]) + .8 barPos = barPos[::-1] #plot.figure(num=None, facecolor='w', edgecolor='r') plot.figure(num=None, facecolor='w') plot.barh(barPos, feature_importance[sorted_idx] * 100, align='center') plot.yticks(barPos, names_cols[sorted_idx]) plot.xticks(np.arange(0, 120, 20), \ ['0 %', '20 %', '40 %', '60 %', '80 %', '100 %']) plot.margins(0.02) plot.subplots_adjust(bottom=0.15) plot.title('Variable Importance') if save: plot.savefig(save_name, bbox_inches='tight', dpi=300) plot.close("all") else: plot.show()
def plot(data, total, grand_total): events = [(e, data[e][0]) for e in data] events.sort(key=lambda x: x[1]) def better_name(n): if n in list(better_names.keys()): return better_names[n] else: return n names = [e[0] for e in events] times = [e[1] for e in events] times_percent = [100.0 * t / float(total) for t in times] if grand_total is not None: comments = ["(%3.1f s, %3.1f%%)" % (time, 100.0 * time / grand_total) for time in times] else: comments = ["(%3.1f s)" % time for time in times] labels = [better_name(name) + " " + comment for name, comment in zip(names, comments)] explode = [0.05]*len(times) plt.pie(times_percent, autopct="%3.1f%%", labels=labels, colors=colors, startangle=0.0, explode=explode) plt.margins(x=0.2, y=0.1) plt.axis('equal')
def superimpose_meas_and_objs_on_image(store_to_image, image, meas, objs): #Consider first up-scaling the image. meas_names = ["Batt_Level", "Num_Poisons", "Num_Foods"] objs_names = ["Battery", "Poison", "Food"] fig, ax = plt.subplots() ax.imshow(image) y_pos = [25, 55, 85] #TODO Generalize objcounter = 0 for obj in objs_names: ax.barh(y_pos[objcounter], convert_plotted_values_x_axis(objs[objcounter]), bar_width, align='center', color=colors[objcounter], ecolor='black') objcounter += 1 ax.text(300, 390, str(meas[0]), fontsize=40, color='blue') ax.legend(objs_names, loc='upper right', fontsize=15) plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(tick.NullLocator()) plt.gca().yaxis.set_major_locator(tick.NullLocator()) plt.savefig(store_to_image, bbox_inches="tight", pad_inches=0) plt.close(fig)
def plot_variable_importance(feature_importance, names_cols, save_name, save): """Show Variable importance graph.""" # scale by max importance first 20 variables in column names feature_importance = feature_importance / feature_importance.max() sorted_idx = np.argsort(feature_importance)[::-1][:20] barPos = np.arange(sorted_idx.shape[0]) + .8 barPos = barPos[::-1] #plot.figure(num=None, facecolor='w', edgecolor='r') plot.figure(num=None, facecolor='w') plot.barh(barPos, feature_importance[sorted_idx]*100, align='center') plot.yticks(barPos, names_cols[sorted_idx]) plot.xticks(np.arange(0, 120, 20), \ ['0 %', '20 %', '40 %', '60 %', '80 %', '100 %']) plot.margins(0.02) plot.subplots_adjust(bottom=0.15) plot.title('Variable Importance') if save: plot.savefig(save_name, bbox_inches='tight', dpi = 300) plot.close("all") else: plot.show()
def feature_importance_plot(self, forest, algorithm): importances = forest.feature_importances_ std = numpy.std( [tree.feature_importances_ for tree in forest.estimators_], axis=0) indices = numpy.argsort(importances)[::-1] print indices labels = [] for index in indices: labels.append(self.header[index]) # Print the feature ranking print("Feature ranking:") for f in range(10): print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) # Plot the feature importances of the forest heights = [] for i in range(10): heights.append(importances[indices[i]]) pylab.figure() pylab.title("Feature importances") pylab.bar(range(10), heights, color="r", align="center") pylab.xticks(range(10), labels, rotation='vertical') pylab.xlim([-1, 10]) pylab.margins(0.2) pylab.subplots_adjust(bottom=0.2) pylab.savefig("features_{0}.png".format(algorithm)) pylab.close()
def borderless_image(image, cmap="hot", fignum=100, filename=None): """Make a nice borderless image.""" plt.figure(fignum) plt.imshow(image, cmap=cmap) plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.show()
def main(): data = open(sys.argv[1], "rb").read() timestamps = [] sampled = [] offset = 0 ts = 0 while offset + DATA_FORMAT.size < len(data): if data[offset] != 0x5a: offset += 1 continue raw_data = DATA_NT._make(DATA_FORMAT.unpack( data[offset + 1:offset + 1 + DATA_FORMAT.size])) scaled_data = DATA_NT( etheta = raw_data.etheta / 255.0 * (2.0 * math.pi), command_d_A = raw_data.command_d_A / 2.0, measured_d_A = raw_data.measured_d_A / 500.0, pid_d_p = raw_data.pid_d_p / 32767.0 * 12.0, pid_d_i = raw_data.pid_d_i / 32767.0 * 12.0, control_d_V = raw_data.control_d_V / 32767.0 * 12.0, velocity = raw_data.velocity / 127.0 * 10.0, bus_V = raw_data.bus_V / 127.0 * 24.0, ) offset += 1 + DATA_FORMAT.size timestamps.append(ts) sampled.append(scaled_data) ts += 1 / 40000.0 fig, ax1 = pylab.subplots() pylab.margins(xmargin=0.2) ax1.plot(timestamps, [x.command_d_A for x in sampled], 'r', label="command") ax1.plot(timestamps, [x.measured_d_A for x in sampled], 'y', label="measured") ax1.plot(timestamps, [x.bus_V for x in sampled], 'gray', label='bus_V') ax1.legend(loc='upper left') ax2 = ax1.twinx() ax2.plot(timestamps, [x.etheta for x in sampled], 'blue', label="etheta") ax2.plot(timestamps, [x.velocity for x in sampled], 'black', label='velocity') ax2.legend(loc='upper right') ax3 = ax1.twinx() ax3.spines['right'].set_position(('outward', 30)) ax3.plot(timestamps, [x.pid_d_p for x in sampled], label='pid.p') ax3.plot(timestamps, [x.pid_d_i for x in sampled], label='pid.i') ax3.plot(timestamps, [x.control_d_V for x in sampled], label='cmd') ax3.legend(loc='lower right') pylab.show()
def binom(self): n = 10 k = np.arange(n + 1) pcoin = stats.binom.pmf(k, n, 0.5) pl.stem(k, pcoin, basefmt='k-') pl.margins(0, 1) pl.savefig('./task1.png') pl.show()
def setup( self, results ): # get the xlabels x = range( 1, len( results ) + 1 ) xlabels = [ r.test.name for r in results ] pylab.title( 'Metric values per test (commit: %s)' % results[0].commit, fontsize=22 ) pylab.xticks( rotation=90 ) pylab.grid( True, markevery='integer' ) pylab.xlabel( 'tests', fontsize=16 ) pylab.margins( 0.05 ) pylab.xticks( x, xlabels )
def gain(abf): """easy way to plot a gain function.""" Ys = np.nan_to_num(swhlab.ap.getAvgBySweep(abf, 'freq')) Xs = abf.clampValues(abf.dataX[int(abf.protoSeqX[1] + .01)]) swhlab.plot.new(abf, title="gain function", xlabel="command current (pA)", ylabel="average inst. freq. (Hz)") pylab.plot(Xs, Ys, '.-', ms=20, alpha=.5, color='b') pylab.axhline(0, alpha=.5, lw=2, color='r', ls="--") pylab.margins(.1, .1)
def setup(self, results): # get the xlabels x = range(1, len(results) + 1) xlabels = [r.test.name for r in results] pylab.title('Metric values per test (commit: %s)' % results[0].commit, fontsize=22) pylab.xticks(rotation=90) pylab.grid(True, markevery='integer') pylab.xlabel('tests', fontsize=16) pylab.margins(0.05) pylab.xticks(x, xlabels)
def Draw_residual(residual_list): x=[i for i in range(1,len(residual_list)+1)] y=residual_list pylab.plot(x,y,'ro') pylab.title("draw residual to check wrong number") # Pad margins so that markers don't get clipped by the axes,让点不与坐标轴重合 pylab.margins(0.3) #绘制网格 pylab.grid(True) pylab.show()
def values_above_sweep(abf, dataI, dataY, ylabel="", useFigure=None): """ To make plots like AP frequency over original trace. dataI=[i] #the i of the sweep dataY=[1.234] #something like inst freq """ xOffset = abf.currentSweep * abf.sweepInterval if not useFigure: #just passing the figure makes it persistant! pylab.figure(figsize=(8, 6)) ax = pylab.subplot(221) pylab.grid(alpha=.5) if len(dataI): pylab.plot(abf.dataX[dataI], dataY, '.', ms=10, alpha=.5, color=abf.colormap[abf.currentSweep]) pylab.margins(0, .1) pylab.ylabel(ylabel) pylab.subplot(223, sharex=ax) pylab.grid(alpha=.5) pylab.plot(abf.dataX, abf.dataY, color=abf.colormap[abf.currentSweep], alpha=.5) pylab.ylabel("raw data (%s)" % abf.units) ax2 = pylab.subplot(222) pylab.grid(alpha=.5) if len(dataI): pylab.plot(abf.dataX[dataI] + xOffset, dataY, '.', ms=10, alpha=.5, color=abf.colormap[abf.currentSweep]) pylab.margins(0, .1) pylab.ylabel(ylabel) pylab.subplot(224, sharex=ax2) pylab.grid(alpha=.5) pylab.plot(abf.dataX + xOffset, abf.dataY, color=abf.colormap[abf.currentSweep]) pylab.ylabel("raw data (%s)" % abf.units) pylab.tight_layout()
def plot_harris_points(image,filtered_coords): pylab.figure() pylab.gray() pylab.imshow(image) pylab.plot([p[1] for p in filtered_coords],[p[0] for p in filtered_coords],"*", color="r") pylab.axis("off") pylab.gca().set_axis_off() pylab.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) pylab.margins(0, 0) pylab.gca().xaxis.set_major_locator(pylab.NullLocator()) pylab.gca().yaxis.set_major_locator(pylab.NullLocator()) pylab.savefig("_1.jpg", bbox_inches='tight', pad_inches=0,dpi=300) pylab.show()
def check_AP_phase(abf, n=10): """X""" timePoints = get_AP_timepoints(abf)[:10] #first 10 if len(timePoints) == 0: return swhlab.plot.new(abf, True, title="AP phase (n=%d)" % n, xlabel="mV", ylabel="V/S") Ys = abf.get_data_around(timePoints, msDeriv=.1, padding=.005) Xs = abf.get_data_around(timePoints, padding=.005) for i in range(1, len(Ys)): pylab.plot(Xs[i], Ys[i], alpha=.2, color='b') pylab.plot(Xs[0], Ys[0], alpha=.4, color='r', lw=1) pylab.margins(.1, .1)
def plot_standard4(abf=exampleABF): """make a standard memtest plot showing Ih, Ra, etc. with time.""" if abf.sweeps < 2: return swhlab.plot.new(abf) Xs = np.arange(abf.sweeps) * abf.sweepInterval / 60 subplots = [221, 222, 223, 224] features = ['Ih', 'Ra', 'Rm', 'Cm'] units = ['pA', 'MOhm', 'MOhm', 'pF'] for subplot, feature, unit in zip(subplots, features, units): pylab.subplot(subplot) pylab.grid(alpha=.5) #pylab.title(feature) pylab.plot(Xs, cm.dictVals(abf.MTs, feature), '.-', alpha=.5) pylab.xlabel(None) pylab.ylabel("%s (%s)" % (feature, unit)) swhlab.plot.comments(abf, True) pylab.margins(0, .1)
def check_AP_deriv(abf, n=10): """X""" timePoints = get_AP_timepoints(abf)[:10] #first 10 if len(timePoints) == 0: return swhlab.plot.new(abf, True, title="AP velocity (n=%d)" % n, xlabel="ms", ylabel="V/S") pylab.axhline(-50, color='r', lw=2, ls="--", alpha=.2) pylab.axhline(-100, color='r', lw=2, ls="--", alpha=.2) Ys = abf.get_data_around(timePoints, msDeriv=.1, padding=.005) Xs = (np.arange(len(Ys[0])) - len(Ys[0]) / 2) * 1000 / abf.rate for i in range(1, len(Ys)): pylab.plot(Xs, Ys[i], alpha=.2, color='b') pylab.plot(Xs, Ys[0], alpha=.4, color='r', lw=2) pylab.margins(0, .1)
def check_AP_raw(abf, n=10): """X""" timePoints = get_AP_timepoints(abf)[:n] #first 10 if len(timePoints) == 0: return swhlab.plot.new(abf, True, title="AP shape (n=%d)" % n, xlabel="ms") Ys = abf.get_data_around(timePoints, padding=.2) Xs = (np.arange(len(Ys[0])) - len(Ys[0]) / 2) * 1000 / abf.rate for i in range(1, len(Ys)): pylab.plot(Xs, Ys[i], alpha=.2, color='b') pylab.plot(Xs, Ys[0], alpha=.4, color='r', lw=2) pylab.margins(0, .1) msg = cm.msgDict(cm.dictFlat(abf.APs)[0], cantEndWith="I") pylab.subplots_adjust(right=0.7) pylab.annotate(msg, (.71, .95), ha='left', va='top', xycoords='figure fraction', family='monospace', size=10)
def fits_to_png(ff, outfile, log=False): plt.clf() ax = plt.axes() fim = ff[1].data # replace NaN values with zero for display fim[np.isnan(fim)] = 0.0 # set contrast to something reasonable transform = AsinhStretch() + PercentileInterval(99.5) bfim = transform(fim) ax.imshow(bfim, cmap="gray", origin="lower") circle = plt.Circle((np.shape(fim)[0] / 2 - 1, np.shape(fim)[1] / 2 - 1), 15, color='r', fill=False) ax.add_artist(circle) plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.savefig(outfile, bbox_inches='tight', pad_inches=0)
def plotAntennas(telescope, names, ids, xpos, ypos, antindex, stations, showplot): fig = pl.figure(1) ax = fig.add_subplot(111) if telescope == 'VLBA': labelx = 'Longitude (deg)' labely = 'Latitude (deg)' else: # use m or km units units = ' (m)' if np.median(xpos) > 1e6 or np.median(ypos) > 1e6: xpos /= 1e3 ypos /= 1e3 units = ' (km)' labelx = 'X' + units labely = 'Y' + units if "VLA" in telescope: spacer = ' ' else: spacer = ' ' # plot points and antenna names/ids for i, (x, y, name, station) in enumerate(zip(xpos, ypos, names, stations)): if station and 'OUT' not in station: ax.plot(x, y, 'ro') if antindex: name += ' (' + str(ids[i]) + ')' # set alignment and rotation angle (for VLA) valign, halign, angle = getAntennaLabelProps(telescope, station) # adjust so text is not on the circle: if halign is 'center': y -= 10 ax.text(x, y, ' '+name, size=8, va=valign, ha=halign, rotation=angle, weight='semibold') if showplot: fig.show() pl.xlabel(labelx) pl.ylabel(labely) pl.margins(0.1, 0.1)
def test(testdir='testdata/'): import pylab as plt from matplotlib.pyplot import savefig harmony = harmony_protect() files = file_name(testdir) for i, file in enumerate(files): print(i, file) img = Image.open(file).convert('RGB') ret, hp = harmony.classify_imgpil(img, True) imgblur_general = harmony.general_harmony(img) w, h = img.size ratio = w / h plt.figure(figsize=(9, 4 / ratio)) plt.subplot(1, 3, 1) plt.imshow(img) plt.title('Origin', fontsize=8) plt.axis('off') plt.subplot(1, 3, 2) plt.imshow(img) plt.imshow(hp, alpha=.75) plt.title('Activation', fontsize=8) plt.axis('off') plt.subplot(1, 3, 3) plt.imshow(imgblur_general) plt.title('general', fontsize=8) plt.axis('off') plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0.05, wspace=0.05) plt.margins(0, 0) plt.savefig('results/' + str(i) + '_anti_deepnude.jpg', dpi=160) plt.close()
def sweep_and_protocol(abf): pylab.figure(figsize=(8, 6)) ax = pylab.subplot(211) pylab.ylabel("measurement (%s)" % abf.units) pylab.plot(abf.dataY, color='b') for I in abf.protoX: pylab.axvline(I, color='k', alpha=.5, ls='--') pylab.margins(0, .05) pylab.subplot(212, sharex=ax) pylab.ylabel("command (%s)" % abf.unitsCommand) pylab.plot(abf.protoX, abf.protoY, color='r', marker='.', ms=10, alpha=.2) pylab.margins(0, .05) for px, py, pi in zip(abf.protoX, abf.protoY, range(len(abf.protoY))): msg = "" if pi == 3: msg += " (Xc)" elif pi == 4: msg += " (Xd)" pylab.text(px, py, str(pi) + msg, va='top', ha='center') pylab.margins(.02, .1) pylab.axis([0, 4000, -90, -50])
def graph_spectrogram(mediaFile, tmp_dir, chunk_size, ffmpeg_bin): def extract_wav(mediaFile, tmp_dir): """ extract wav from media file """ wavTmpPath = "{tmp_dir}{sep}{mediaBaseName}.wav".format(tmp_dir=tmp_dir, sep=os.sep, mediaBaseName=os.path.basename(mediaFile)) if os.path.isfile(wavTmpPath): return wavTmpPath else: p = subprocess.Popen('{ffmpeg_bin} -i "{mediaFile}" -y -ac 1 -vn "{wavTmpPath}"'.format(ffmpeg_bin=ffmpeg_bin, mediaFile=mediaFile, wavTmpPath=wavTmpPath), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, error = p.communicate() out, error = out.decode("utf-8"), error.decode("utf-8") if not out: return wavTmpPath else: return None def get_wav_info(wav_file): wav = wave.open(wav_file, "r") frames = wav.readframes(-1) sound_info = pylab.fromstring(frames, "Int16") frame_rate = wav.getframerate() wav.close() return sound_info, frame_rate matplotlib.use("Agg") import pylab fileName1stChunk = '' mediaBaseName = os.path.basename( mediaFile ) wav_file = extract_wav(mediaFile, tmp_dir) if not wav_file: return None sound_info, frame_rate = get_wav_info(wav_file) wav_length = round(len(sound_info) / frame_rate, 3) i = 0 while True: chunkFileName = "{}.{}-{}.spectrogram.png".format(wav_file, i, i + chunk_size) if not os.path.isfile(chunkFileName): sound_info_slice = sound_info[i * frame_rate: (i + chunk_size) * frame_rate] # complete bitmat spectrogram chunk if shorter than chunk length if len(sound_info_slice) / frame_rate < chunk_size: concat = np.zeros((chunk_size - len(sound_info_slice) / frame_rate )* frame_rate) sound_info_slice = np.concatenate((sound_info_slice, concat)) pylab.figure(num=None, dpi=100, figsize=(int( len(sound_info_slice)/frame_rate), 1)) pylab.gca().set_axis_off() pylab.margins(0, 0) pylab.gca().xaxis.set_major_locator(pylab.NullLocator()) pylab.gca().yaxis.set_major_locator(pylab.NullLocator()) #pylab.specgram(sound_info_slice, Fs=frame_rate, cmap=matplotlib.pyplot.get_cmap('Greys'),scale_by_freq=False) pylab.specgram(sound_info_slice, Fs=frame_rate, scale_by_freq=False) pylab.savefig(chunkFileName, bbox_inches='tight', pad_inches=0) pylab.clf() pylab.close() if not fileName1stChunk: fileName1stChunk = chunkFileName i += chunk_size if i >= wav_length: break return fileName1stChunk
def check_sweep(abf, sweep=None, dT=.1): """Plotting for an eyeball check of AP detection in the given sweep.""" if abf.APs is None: APs = [] else: APs = cm.matrixToDicts(abf.APs) if sweep is None or len( sweep) == 0: #find the first sweep with >5APs in it for sweepNum in range(abf.sweeps): foundInThisSweep = 0 for AP in APs: if AP["sweep"] == sweepNum: foundInThisSweep += 1 if foundInThisSweep >= 5: break sweep = sweepNum abf.setSweep(sweep) Y = abf.dataY dI = int(dT / 1000 * abf.rate) #dI is dT/rate dY = (Y[dI:] - Y[:-dI]) * (abf.rate / 1000 / dI) #now in V/S pylab.figure(figsize=(12, 6)) ax = pylab.subplot(211) pylab.title("sweep %d" % abf.currentSweep) pylab.ylabel("membrane potential (mV)") pylab.plot(Y, '-', alpha=.8) for AP in APs: if not AP["sweep"] == sweep: continue pylab.axvline(AP["sweepI"], alpha=.2, color='r') pylab.plot(AP["peakI"], AP["peak"], '.', alpha=.5, ms=20, color='r') pylab.plot(AP["thresholdI"], AP["threshold"], '.', alpha=.5, ms=20, color='c') pylab.plot([AP["AHPI"], AP["AHPreturnI"]], [AP["AHP"], AP["AHPreturn"]], '-', alpha=.2, ms=20, color='b', lw=7) pylab.plot([AP["halfwidthI1"], AP["halfwidthI2"]], [AP["halfwidthPoint"], AP["halfwidthPoint"]], '-', lw=5, alpha=.5, color='g') pylab.subplot(212, sharex=ax) pylab.ylabel("velocity (V/S)") pylab.xlabel("data points (%.02f kHz)" % (abf.rate / 1000)) pylab.plot(dY, '-', alpha=.8) pylab.margins(0, .1) for AP in APs: if not AP["sweep"] == sweep: continue pylab.axvline(AP["sweepI"], alpha=.2, color='r') pylab.plot(AP["upslopeI"], AP["upslope"], '.', alpha=.5, ms=20, color='g') pylab.plot(AP["downslopeI"], AP["downslope"], '.', alpha=.5, ms=20, color='g') pylab.axis( [APs[0]["sweepI"] - 1000, APs[-1]["sweepI"] + 1000, None, None])
log_values = 100 * 2**np.arange(0, np.log2(i_tr[-1] / 100), 0.1) print log_values crit = (np.mod(i_tr, 2000) == 0) crit = np.in1d(i_tr, log_values) #crit = (np.mod(i_tr, 500) == 0) pl.clf() #pl.plot (i_tr[crit], e_tr[crit], label = "Training set") pl.plot(i_tr, e_tr, "k:", label="Training set") pl.plot(i_val, e_val, "k-", label="Validation set", lw=2) #pl.axhline (test, ls = ":", label = "Test set", color = "k") pl.scatter([i_tr[-1]], [test], c="b", marker="x", s=300, label="Test set") pl.legend(loc="best", scatterpoints=1) pl.ylim([0, 0.05]) #pl.yscale("log") pl.margins(x=0.05) pl.xlabel("iteration") pl.ylabel("error") pl.savefig(sys.argv[1] + "/learning_history.eps") pl.clf() pl.hist(e_tr, bins=1000) pl.savefig("hist_etrain") exit() pl.plot(i_tr, e_tr, label="Training set") pl.plot(i_val, e_val, label="Validation set") pl.legend(loc="best") pl.xlim([-1, 10000]) #pl.ylim([0, 0.02]) pl.savefig(sys.argv[1] + "/learning_history") # pl.plot (i_tr, e_tr, label = "Training set")
def draw(self): """ Redraw the plot. First draw stored data, then the current file. """ if self.axes_diff: self.axes_diff.cla() self.axes.cla() pl.sca(self.axes) # Plot stored data self.dataset.plot(self.axes) filename = self.spelist[0] # Plot current spectrum x, y = self.reader.read_spe(filename) if self.visible: self.axes.plot(x, y, line_colors.default, lw=1.25, label=mklbl(filename)) # Plot difference (if any) if self.diffdata and self.axes_diff: y, label = self.diffdata self.axes_diff.plot(x, y, line_colors.diff, linestyle="-", lw=0.8, label=label, alpha=0.7) legend_diff = self.axes_diff.legend(loc="center right", fontsize="small", fancybox=True, frameon=True, framealpha=0.6) legend_diff.draggable(True) legend_diff.set_title("Difference") self.axes_diff.set_ylabel("Difference in counts", color=line_colors.diff) self.axes_diff.hlines(0, min(x), max(x), color=line_colors.diff, linestyles="--", lw=.75, alpha=.5) for tl in self.axes_diff.get_yticklabels(): tl.set_color(line_colors.diff) pl.sca(self.axes) # change figure title and plot params self.canvas.set_window_title(filename) # Formatting - zero level, limits of axes self.axes.set_xlim(min(x), max(x)) pl.margins(0.0, 0.05) # 5% vertical margins self.axes.yaxis.get_major_formatter().set_powerlimits((0, 4)) self.axes.yaxis.get_major_formatter().set_powerlimits((0, 4)) # Formatting - labels and title pl.ylabel("Counts") pl.title(filename) if self.reader.calibrated: pl.xlabel("Wavenumber, cm$^{-1}$") else: pl.xlabel("pixel number") # Formatting - legend if self.visible or len(self.dataset.get_lines()): pl.hlines(0, min(x), max(x), "k", linestyles="--", lw=.7, alpha=.5) legend = pl.legend(loc="upper right", fontsize="small", fancybox=True, frameon=True, framealpha=0.6) legend.draggable(True) if len(legend.get_texts()) > 1: legend.set_title("Opened files") else: legend.set_title("Opened file") self.axes.yaxis.set_visible(True) else: self.axes.yaxis.set_visible(False) if self.grid: self.axes.grid(self.grid, which='major', axis='both') # Display program help if self.help is True: self.help = \ self.figure.text(0.05, 0.5, KEYSTROKES, fontsize="medium", ha="left", va="center", family="monospace", bbox=self.boxprops) # Display the file-related information if self.show_info is True: self.axes.text(x.min(), 0.0, self.reader.read_info(filename), fontsize="medium", ha="left", va="bottom", family="monospace", bbox=self.boxprops) self.canvas.draw()
for ml in match_list: frame_number = 0; print('Working on locus: ' + ml); df_add = [] global locus_loc_y; global locus_loc_x; locus_loc_y = 0; locus_loc_x = 0; local_data = np.zeros(frames, local_size, local_size, np.int16); min_pix = np.min(im[np.nonzero(im)]) max_pix = np.max(im[np.nonzero(im)]) fig = plt.figure(figsize=(5,5), frameon=False); ax = fig.add_axes([0,0,1,1], xlim=(0,x_size), ylim=(y_size,0), aspect='equal', frameon=False); ax.set_axis_off(); plt.margins(0,0) ax.set_frame_on(False); ax.set_xlim([0, x_size]); ax.set_ylim([y_size, 0]); data = im[frame_number,:,:]; # Create x and y indices x_pixels, y_pixels = data.shape x = np.linspace(0, x_pixels - 1, x_pixels); y = np.linspace(0, y_pixels - 1, y_pixels); x,y = np.meshgrid(x, y); implt = plt.imshow(data, cmap=plt.cm.gray, vmin=min_pix, vmax=max_pix); blank_contour = np.ones((x_pixels, y_pixels));
def graph_spectrogram(mediaFile, tmp_dir, chunk_size, ffmpeg_bin, spectrogramHeight, spectrogram_color_map): def extract_wav(mediaFile, tmp_dir): """ extract wav from media file """ wavTmpPath = "{tmp_dir}{sep}{mediaBaseName}.wav".format( tmp_dir=tmp_dir, sep=os.sep, mediaBaseName=os.path.basename(mediaFile)) if os.path.isfile(wavTmpPath): return wavTmpPath else: p = subprocess.Popen( '"{ffmpeg_bin}" -i "{mediaFile}" -y -ac 1 -vn "{wavTmpPath}"'. format(ffmpeg_bin=ffmpeg_bin, mediaFile=mediaFile, wavTmpPath=wavTmpPath), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, error = p.communicate() out, error = out.decode("utf-8"), error.decode("utf-8") if "does not contain any stream" not in error: return wavTmpPath else: return "" def get_wav_info(wav_file): """ fetch information from wav file Args: wav_file (str): path of wav file Returns: : info on sound int: frame_rate """ wav = wave.open(wav_file, "r") frames = wav.readframes(-1) sound_info = pylab.fromstring(frames, "Int16") frame_rate = wav.getframerate() wav.close() return sound_info, frame_rate if QT_VERSION_STR[0] == "4": matplotlib.use("Qt4Agg") else: matplotlib.use("Qt5Agg") import pylab # do not move. It is important that this line is after the previous one fileName1stChunk = "" mediaBaseName = os.path.basename(mediaFile) wav_file = extract_wav(mediaFile, tmp_dir) if not wav_file: return None sound_info, frame_rate = get_wav_info(wav_file) wav_length = round(len(sound_info) / frame_rate, 3) i = 0 while True: chunkFileName = "{}.{}-{}.{}.{}.spectrogram.png".format( wav_file, i, i + chunk_size, spectrogram_color_map, spectrogramHeight) if not os.path.isfile(chunkFileName): sound_info_slice = sound_info[i * frame_rate:(i + chunk_size) * frame_rate] # complete bitmat spectrogram chunk if shorter than chunk length if len(sound_info_slice) / frame_rate < chunk_size: concat = np.zeros( int((chunk_size - len(sound_info_slice) / frame_rate) + 1) * frame_rate) sound_info_slice = np.concatenate((sound_info_slice, concat)) pylab.figure(num=None, dpi=100, figsize=(int(len(sound_info_slice) / frame_rate), round(spectrogramHeight / 80))) pylab.gca().set_axis_off() pylab.margins(0, 0) pylab.gca().xaxis.set_major_locator(pylab.NullLocator()) pylab.gca().yaxis.set_major_locator(pylab.NullLocator()) try: pylab.specgram( sound_info_slice, Fs=frame_rate, cmap=matplotlib.pyplot.get_cmap(spectrogram_color_map), scale_by_freq=False) except ValueError: # color_map gray_r is available on all version of matplotlib pylab.specgram(sound_info_slice, Fs=frame_rate, cmap=matplotlib.pyplot.get_cmap("gray_r"), scale_by_freq=False) pylab.savefig(chunkFileName, bbox_inches="tight", pad_inches=0) pylab.clf() pylab.close() if not fileName1stChunk: fileName1stChunk = chunkFileName i += chunk_size if i >= wav_length: break return fileName1stChunk
print filestr F = open(filestr,'r') T,RMS = [],[] label,badlist,goodlist = [],[],[] rmsbound = float(sys.argv[1:][1]) c = 0 print 'BAD:' for line in F: L = line.split() T.append(float(L[0][4:17])) RMS.append(float(L[1])) label.append(L[0][0:17]) if float(L[1]) >= rmsbound: print float(L[0][4:17]), float(L[1]) badlist.append(L[0]) else: goodlist.append(L[0]) c+=1 pylab.plot(T,RMS,'-',lw=2) pylab.axhline(rmsbound,linestyle='--',color='k') pylab.margins(0.2) pylab.show() pylab.close() print 'GOOD:',len(goodlist),'/',c,'rms-bound of %f'%rmsbound
plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.grid() plt.subplot(2, 3, 5) plt.plot(freqs_band, np.abs(bandpass_f), 'r') plt.xlabel('Freq [Hz]') plt.ylabel('|Y(freq)|') plt.grid() plt.subplot(2, 3, 3) plt.semilogx(w, 20 * np.log10(abs(h))) plt.title('Butterworth filter frequency response') plt.xlabel('Freq [rad/s]') plt.ylabel('Amplitude [dB]') plt.margins(0, 0.1) plt.grid(which='both', axis='both') plt.show() # overlapping frames frame_length = 20e-3 # in seconds, ie. 20ms samples_per_frame = math.ceil(frame_length / ts) step = samples_per_frame // 2 # integer division, Python 3.x only frames = [] for i in range(0, len(signal), step): frame = signal[i:(frame_length + i)] frames.append(frame) # save those frames somewhere?
for m in results.keys(): pl.clf() pl.xlabel(parameter1) pl.xticks(map(float,parameter1Values)) pl.ylabel(m) maxy = -1 i=0 for plotv in parameter2Values: values = filter(lambda x: x[1]==plotv, results[m]) x, _, y, std = zip(*values) if maxy < max(y): maxy = max(y) x = map(float, x) plot_label = '%s=%s'%(parameter2, plotv) curr_format = formatStrings[i] pl.errorbar(x, y, yerr=std, fmt=curr_format, label=plot_label) i = (i+1)%len(formatStrings) pl.margins(0.05, 0.05) pl.legend(loc='best') pl.savefig( plot_dir + '/m2d_%s_vs_%s_vs_%s.png' % (m, parameter1, parameter2) ) #pl.show() param_file = open(plot_dir + '/params.txt', 'w') param_file.write( ' '.join(argv) ) param_file.write( '\n' ) param_file.close()
print "time for string replacement: ", t2-t1, "s" lines, points, lines_idx = turtle_lines(s, delta, d, "FGf", "") t3 = time.time() print "time for lines creation: ", t3-t2, "s" export_collada("/tmp/frac.dae", points, lines_idx) t4 = time.time() print "time for collada export: ", t4-t3, "s" print "number of lines: ", len(points) #print s fig, ax = plt.subplots() if plot3D==False: ############# 2D #plt.plot(*zip(*points), color="b") for l in lines: plt.plot([l[0][1],l[1][1]], [l[0][0],l[1][0]], color="b") plt.margins(x=.1, y=.1) plt.xlabel("x") else: ############# 3D ax = fig.add_subplot(111, projection='3d') #ax.plot(points[:,2], points[:,1], points[:,1], color="b") plt.plot([0.], [0.], [0.], "o", color="r") for l in lines: ax.plot( [l[0][2],l[1][2]], [l[0][1],l[1][1]], [l[0][0],l[1][0]], color='blue') ax.set_zlabel("x") plt.margins(.1) plt.xlabel("z") plt.ylabel("y") plt.show() #block=False)
import sys D = np.loadtxt(sys.argv[1]) X = D[:, 0] Y = D[:, 1] perfect = [Y[0] / 2**i for i in range(len(X))] # Y2 = D[:,2] # Y3 = D[:,3] for x in X: pylab.axvline(x, color="k", linewidth=0.1) pylab.xscale("log") pylab.yscale("log") # pylab.axvspan(641, X.max(), facecolor='g', alpha=0.5) pylab.plot(X, Y, label="batch size = 1000") pylab.plot(X, perfect, "k--", label="perfect scaling") # pylab.plot(X,Y2, label="batch size = 10000") # pylab.plot(X,Y3, label="batch size = 100000") pylab.xlim((X.min(), X.max())) pylab.xlabel("# nodes") pylab.ylabel("time/s") pylab.margins(0.2) pylab.subplots_adjust(bottom=0.20) pylab.legend() pylab.title("Scaling behaviour of processing 1 billion particles on HASWELL") pylab.xticks(X, [str(int(x)) for x in X]) #, rotation='vertical') pylab.savefig(sys.argv[2])
sim.end() print("Total number of spikes %d" % (len(spikes['target']))) ######################################################################## # P L O T R E S U L T S ######################################################################## # print(voltage) fig = plt.figure() ax = plt.subplot(1, 1, 1) plt.plot([t for _, t, _ in voltage], [v for _, _, v in voltage]) plt.draw() plt.savefig("characterize_neuron_voltage.png", dpi=300) # Spikes fig = plt.figure() ax = plt.subplot(1, 1, 1) nids = [nid for (nid, spkt) in spikes['source']] spkts = [spkt for (nid, spkt) in spikes['source']] plt.plot(spkts, nids, '^g', markersize=4) nids = [nid for (nid, spkt) in spikes['target']] spkts = [spkt for (nid, spkt) in spikes['target']] plt.plot(spkts, nids, 'ob', markersize=4) plt.ylim(-1, num_neurons + 1) plt.draw() plt.margins(0.05, 0.05) plt.savefig("characterize_spike_activity.png", dpi=300) # plt.show() plt.close(fig)
plt.errorbar(h_in[('L')].index.values, h_in[('L')], yerr=h_in_err[('L')].values, marker='o', color='#85c1fe', label="L") plt.errorbar(h_in[('R')].index.values, h_in[('R')], yerr=h_in_err[('R')].values, marker='o', color='orange', label="R") plt.ylabel(u"Zählrate (kHz)") ax.locator_params(tight=True, nbins=6) plt.legend(title='Polarisation', fancybox=True, loc='upper left') plt.margins(0, .1) plt.ylim(ymin=0) #plt.text(10.83,20, r'$N_{\mathrm{in}} = \SI{%.1f}{}$' % N_in + '\n' + # r'$\epsilon_{R\mathrm{, in}} = \SI{%s}{\percent}$' % un2str(ext0*100, ext0_err*100), ha='center' ) plot_dict = {} h_L = pd.DataFrame(index=h_in[('L')].index.values - 11.0, data=watt_factor * h_in[('L')].values) h_L_err = pd.DataFrame(index=h_in[('L')].index.values - 11.0, data=watt_factor * h_in_err[('L')].values) h_R = pd.DataFrame(index=h_in[('R')].index.values - 11.0, data=watt_factor * h_in[('R')].values) h_R_err = pd.DataFrame(index=h_in[('R')].index.values - 11.0, data=watt_factor * h_in_err[('R')].values)
lines, points, lines_idx = turtle_lines(s, delta, d, "FGf", "") t3 = time.time() print "time for lines creation: ", t3 - t2, "s" export_collada("/tmp/frac.dae", points, lines_idx) t4 = time.time() print "time for collada export: ", t4 - t3, "s" print "number of lines: ", len(points) #print s fig, ax = plt.subplots() if plot3D == False: ############# 2D #plt.plot(*zip(*points), color="b") for l in lines: plt.plot([l[0][1], l[1][1]], [l[0][0], l[1][0]], color="b") plt.margins(x=.1, y=.1) plt.xlabel("x") else: ############# 3D ax = fig.add_subplot(111, projection='3d') #ax.plot(points[:,2], points[:,1], points[:,1], color="b") plt.plot([0.], [0.], [0.], "o", color="r") for l in lines: ax.plot([l[0][2], l[1][2]], [l[0][1], l[1][1]], [l[0][0], l[1][0]], color='blue') ax.set_zlabel("x") plt.margins(.1) plt.xlabel("z") plt.ylabel("y") plt.show() #block=False)
pl.errorbar(xPos[0], Ex11_Bias[Input_Mass_Col], yerr = [[Ex11_Bias[Mass_Error_Cols[1]]],[Ex11_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[0], Ex12_Bias[Input_Mass_Col], yerr = [[Ex12_Bias[Mass_Error_Cols[1]]],[Ex12_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[1], Ex21_Bias[Input_Mass_Col], yerr = [[Ex21_Bias[Mass_Error_Cols[1]]],[Ex21_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[1], Ex22_Bias[Input_Mass_Col], yerr = [[Ex22_Bias[Mass_Error_Cols[1]]],[Ex22_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[2], Ex31_Bias[Input_Mass_Col], yerr = [[Ex31_Bias[Mass_Error_Cols[1]]],[Ex31_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[2], Ex32_Bias[Input_Mass_Col], yerr = [[Ex32_Bias[Mass_Error_Cols[1]]],[Ex32_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[3], Ex41_Bias[Input_Mass_Col], yerr = [[Ex41_Bias[Mass_Error_Cols[1]]],[Ex41_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.errorbar(xPos[3], Ex42_Bias[Input_Mass_Col], yerr = [[Ex42_Bias[Mass_Error_Cols[1]]],[Ex42_Bias[Mass_Error_Cols[0]]]], color = Experiment_Colour[0], linewidth = 3., marker = 'x') pl.margins(0.1) pl.subplots_adjust(bottom = 0.25) #Plot Input Mass line xmin, xmax = pl.xlim() pl.plot((xmin, xmax), (Ex11_Bias[Input_Mass_Col]-Ex11_Bias[Mass_Bias_Col],Ex11_Bias[Input_Mass_Col]-Ex11_Bias[Mass_Bias_Col]), linestyle = '--', color = 'k') pl.plot((xmin, xmax), (Ex12_Bias[Input_Mass_Col]-Ex12_Bias[Mass_Bias_Col],Ex12_Bias[Input_Mass_Col]-Ex12_Bias[Mass_Bias_Col]), linestyle = '--', color = 'k') pl.xticks(xPos, Experiment_Labels, rotation = 45.) pl.ylabel(r'Mass $\left(M_{200}\; \left[\frac{\rm M_\odot}{h}\right]\right)$') if(do_Logscale): pl.yscale('log') pl.show()
import numpy as np import pylab as pl from lib import read_from_file from main import num_e, num_i, t_final data = np.loadtxt("data.txt") g = data[:, 0] delta = data[:, 1] f = data[:, 2] fig, ax = pl.subplots(ncols=2, figsize=(8, 3.5)) ax[0].plot(g, delta, lw=2, c='k') ax[1].plot(g, f, lw=2, c='k') ax[0].set_ylabel(r"$\Delta$", fontsize=13) ax[1].set_ylabel(r"$f$", fontsize=13) for i in range(2): ax[i].set_xlabel(r"$\bar{g_{EE}}$", fontsize=13) ax[i].tick_params(labelsize=13) pl.margins(x=0.01) pl.tight_layout() pl.savefig("fig.png")