def get_dataset_color(dataset,depth=None): """Set the colors to ensure a uniform scheme for each dataset """ dataset=string.lower(dataset) d={} d["dai"]=cm.Blues(.5) d["tree"]=cm.summer(.3) d["cru"]=cm.Blues(.9) #models d["picontrol"]=cm.Purples(.8) d["h85"]="k" d["tree_noise"]=cm.PiYG(.2) #Soil moisture d["merra2"]={} d["merra2"]["30cm"]=cm.copper(.3) d["merra2"]["2m"]=cm.copper(.3) d["gleam"]={} d["gleam"]["30cm"]=cm.Reds(.3) d["gleam"]["2m"]=cm.Reds(.7) if depth is None: return d[dataset] else: return d[dataset][depth]
def get_color(self, watson, gene_type): colors = { "Verified": cm.Blues(0.7), "Putative": cm.Blues(0.35), "Dubious": "#898888" } if not watson: colors['Verified'] = cm.Reds(0.5) colors['Putative'] = cm.Reds(0.3) colors['Uncharacterized'] = colors['Putative'] color = colors[gene_type] return color
def NatureRevisions_Figure3(D,start_year=2019): plt.subplot(311) Plotting.time_plot(D.ALL.get_noise(),color=get_dataset_color("tree"),label="Pre-industrial Noise",lw=1) Plotting.time_plot(D.ALL.projection(time=('1850-1-1','1975-12-31')),c="k",lw=1) plt.ylabel("Projection (temporal amplitude)",fontsize=8) plt.xlabel("Year") plt.legend() plt.title("(a)")#: Global Drought Atlas Projection Onto Fingerprint",fontsize=8) plt.subplot(312) t1900 = cdtime.comptime(1900,7,1) times = np.arange(1,201) likely=stats.norm.interval(.66)[1] vlikely=stats.norm.interval(.90)[1] certain=stats.norm.interval(.99)[1] plt.axhline(likely,lw=1,color=cm.Reds(.33),label="Likely",alpha=.5) plt.axhline(vlikely,lw=1,color=cm.Reds(.66),label="Very Likely",alpha=.5) plt.axhline(certain,lw=1,color=cm.Reds(.99),label="Virtually Certain",alpha=.5) D.ALL.time_of_emergence(t1900,times=times,color="k",lw=3) pdsi_SN_figure(D,cdtime.comptime(1900,1,1),use_dai=True) plt.title("(b)")#: Model-predicted time of emergence",fontsize=8) plt.subplot(313) hist_start = cdtime.comptime(1900,1,1) times = np.arange(10,2100-start_year) for X in ["ALL","ANZDA","MADA","MXDA","NADA","OWDA"]: getattr(D,X).time_of_emergence(cdtime.comptime(start_year,1,1),times=times,color=colorregions(X),uncertainty="shade") certain=stats.norm.interval(.99)[1] plt.axhline(certain,lw=1,color=cm.Reds(.99),label="Virtually Certain", alpha=.5) plt.title("(c)")#: Time of Emergence (assuming "+str(start_year)+" start)",fontsize=8) ax1,ax2,ax3=plt.gcf().axes ax2.set_xlim(1900,2055) ax2.set_ylim(-3,7) for ax in [ax1,ax2,ax3]: ax.set_xlabel(ax.get_xlabel(),fontsize=8) ax.set_ylabel(ax.get_ylabel(),fontsize=8) ax3.set_xlim(start_year+10,start_year+55) ax2.legend(fontsize=6) ax3.legend(fontsize=6) ax1.legend(fontsize=6) for ax in plt.gcf().axes: plt.setp(ax.get_xticklabels(),fontsize=6) plt.setp(ax.get_yticklabels(),fontsize=6) plt.setp(ax.xaxis.get_label(),fontsize=6) plt.setp(ax.yaxis.get_label(),fontsize=6)
def plot_seed_and_gen(seedhist, genhist, figname='fig.png'): # plot all histograms in seedhist (data), and genhist (generated) # input: # - datahist, genhist: numpy arrays of shape (nhists,nbins) # - figname: name of figure to plot # make sure that figname contains absolute path figname = os.path.abspath(figname) nresamp = int(genhist.shape[0] / seedhist.shape[0]) # data plt.figure() gen_colors = [cm.viridis(i) for i in np.linspace(0, 1, len(genhist))] seed_colors = [cm.Reds(i) for i in np.linspace(0, 1, len(seedhist))] for i in range(len(genhist)): plt.plot(genhist[i, :], color=gen_colors[i]) for i in range(len(seedhist)): plt.plot(seedhist[i, :], color='r', label='seed') plt.title('seed and resampled histograms') plt.legend() plt.savefig(figname.split('.')[0] + '_show.png') plt.close() if nresamp != genhist.shape[0]: plt.figure() for i in range(len(seedhist)): for j in range(i * nresamp, (i + 1) * nresamp): plt.plot(genhist[j, :], color=gen_colors[j]) plt.plot(seedhist[i, :], color='r', label='seed') plt.title('seed and resampled histograms') plt.legend() plt.savefig(figname.split('.')[0] + '_show' + str(i) + '.png') plt.close()
def test_illustris(): zs = np.linspace(0.,3.,4)[:1] ms = np.geomspace(1e8,1e16,1000) ks = np.geomspace(1e-2,30,1001) hcos = hmvec.HaloModel(zs,ks,ms=ms,halofit=None,mdef='vir',nfw_numeric=False) hcos.add_battaglia_profile("electron",family="AGN",xmax=50,nxs=30000) pee = hcos.get_power("electron") pnn = hcos.get_power("nfw") pne = hcos.get_power("nfw","electron") p1 = hcos.total_matter_power_spectrum(pnn,pne,pee) p0 = pnn h = hcos.h from matplotlib import cm pl = io.Plotter(xyscale='loglin',xlabel='$k$ (h/Mpc)',ylabel='$\\Delta P / P$') for i in range(zs.size): pl.add(ks/h,p1[i]/p0[i],color=cm.Reds(np.linspace(0.3,0.95,zs.size)[::-1][i]),label='hmvec + Battaglia') ok,od = np.loadtxt("data/schneider_horizon_agn.csv",delimiter=',',unpack=True) pl.add(ok,od,lw=2,color='k',label='Horizon AGN') ok,od = np.loadtxt("data/schneider_owls.csv",delimiter=',',unpack=True) pl.add(ok,od,lw=2,color='k',ls='--',label='OWLS') pl.vline(x=10.) pl.hline(y=1.) pl._ax.set_ylim(0.68,1.04) pl._ax.set_xlim(0.08,25) pl.done("illustris_comp.png")
def plot_single_trajectory(t, ts, ax, thr=0.3): # plot absolute from matplotlib import cm ax[0].set_ylim(-5, 5000) #np.round((np.max(ts[2])/1000)+1)*1000) lineages = [['1.p', '1.pp', '1.ppp'], ['4.a', '4.aa', '4.aaa']] col = np.array([ np.array([ cm.Blues(int(i))[:3] for i in (np.arange(len(lineages[0])) * 254. / (len(lineages[0]) - 1) / 254.) * 127 + 127 ]), np.array([ cm.Reds(int(i))[:3] for i in (np.arange(len(lineages[0])) * 254. / (len(lineages[0]) - 1) / 254.) * 127 + 127 ]) ]) for c in [0, 1]: for j in [0, 1, 2]: ax[0].plot(t[j] / 60., ts[j][:, c], '-', color=col[c, j], lw=2) # plot ratio col = 'kcm' diff_D = [] for j in [0, 1, 2]: diff_D.append( (ts[j][:, 0] - ts[j][:, 1]) / (ts[j][:, 0] + ts[j][:, 1])) ax[1].plot(t[j] / 60., diff_D[j], '-' + col[j], lw=2) # get T_decision (AC_id, T_dec, ind) = get_T_decision(t, ts, 0.3) # and plot in figure if len(ind) > 0: ax[1].plot(t[ind[0]][ind[1]] / 60., diff_D[ind[0]][ind[1]], 'ok')
def scale_colors(sizes, shapes): """ Scales colors so they aren't all faded out. Returns R/G/B scales. :param sizes: List of sizes :param shapes: List of shapes :return: Colormap object """ size_set = sorted(list(set(sizes))) linspace = np.linspace(0.2, 1, len(size_set)) redmap = cm.Reds(linspace) greenmap = cm.Greens(linspace) bluemap = cm.Blues(linspace) colors = [] for size, shape in zip(sizes, shapes): if shape == "icosahedron": # Red colors.append(redmap[size_set.index(size)]) elif shape == "elongated-pentagonal-bipyramid": # Green colors.append(greenmap[size_set.index(size)]) elif shape == "cuboctahedron": # Blue colors.append(bluemap[size_set.index(size)]) else: raise ValueError return colors
def plot_figure(self, x_labels, y_vals): """ Creates the plot with the given x and y values. Also sets the visual params. :param x_labels: names of players (used for labels) :param y_vals: values of ownership. :return: """ width = 0.35 x_vals = range(self.ncols) for i in range(self.ncols): color_val = y_vals[i] / 100.0 + 0.4 if color_val > 1.0: color_val = 1.0 self.axes.bar(x_vals[i] + width, y_vals[i], width=width, color=cm.Reds(color_val)) # Set the visual options of the plots self.axes.set_xticks([x + width * 3 / 2 for x in x_vals]) self.axes.set_xticklabels(x_labels, rotation=90, size=7) self.axes.set_yticks(range(0, 110, 10)) self.axes.tick_params(axis='y', labelsize=8) self.axes.set_title(self.position, fontsize=10) self.axes.set_axis_bgcolor('#242426') self.axes.grid(axis='y', color='w', linestyle='-') self.axes.set_axisbelow(True)
def get_strand_colors(num_times=6): # colors color_offset = 2 N = num_times + color_offset blues = map(lambda x: cm.Blues(float(x) / (N), 1), range(color_offset, N)) reds = map(lambda x: cm.Reds(float(x) / (N), 1), range(color_offset, N)) return reds, blues
def get_ib_config(): nodes = [4, 8, 16, 32] fpaths, tags, legends, colors = [], [], [], [] ps_ib_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ps_ib_tags = [ 'SIMPLE-PS-SGD-4IB', 'SIMPLE-PS-SGD-8IB', 'SIMPLE-PS-SGD-16IB', 'SIMPLE-PS-SGD-32IB-4' ] ps_ib_legends = [ 'SGP 4 nodes', 'SGP 8 nodes', 'SGP 16 nodes', 'SGP 32 nodes' ] ps_ib_colors = [ cm.Blues(x) for x in np.linspace(0.3, 0.8, len(ps_ib_tags)) ] fpaths.append(ps_ib_fpath) tags.append(ps_ib_tags) legends.append(ps_ib_legends) colors.append(ps_ib_colors) ar_ib_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ar_ib_tags = [ 'AR-DPSGD-CPUCOMM-4IB-SCRATCh', 'AR-DPSGD-CPUCOMM-8IB-SCRATCh', 'AR-DPSGD-CPUCOMM-16IB-SCRATCh', 'AR-DPSGD-CPUCOMM-32IB-SCRATCH' ] ar_ib_legends = [ 'AR-SGD 4 nodes', 'AR-SGD 8 nodes', 'AR-SGD 16 nodes', 'AR-SGD 32 nodes' ] ar_ib_colors = [cm.Reds(x) for x in np.linspace(0.3, 0.8, len(ar_ib_tags))] fpaths.append(ar_ib_fpath) tags.append(ar_ib_tags) legends.append(ar_ib_legends) colors.append(ar_ib_colors) return nodes, fpaths, tags, legends, colors
def test_illustris(): zs = np.linspace(0., 3., 4) ms = np.geomspace(1e8, 1e16, 1000) ks = np.geomspace(1e-2, 30, 1001) hcos = hmvec.HaloModel(zs, ks, ms=ms, halofit=None, mdef='vir', nfw_numeric=False) hcos.add_battaglia_profile("electron", family="AGN", xmax=50, nxs=30000) pee = hcos.get_power("electron") pnn = hcos.get_power("nfw") pne = hcos.get_power("nfw", "electron") p1 = hcos.total_matter_power_spectrum(pnn, pne, pee) p0 = pnn h = hcos.h from matplotlib import cm pl = io.Plotter(xyscale='loglin', xlabel='$k$ (h/Mpc)', ylabel='$\\Delta P / P$') for i in range(zs.size): pl.add(ks / h, p1[i] / p0[i], color=cm.Reds(np.linspace(0.3, 0.95, zs.size)[i])) pl.vline(x=10.) pl.hline(y=1.) pl._ax.set_ylim(0.68, 1.04) pl._ax.set_xlim(0.08, 25) pl.done("illustris_comp.png")
def da_colors(typ): d = {} d["h85"] = cm.Oranges(.8) #cm.Dark2(0.) d["piC"] = cm.Greens(.7) #cm.Dark2(.2) d["gpcp"] = cm.Purples(.5) #cm.Dark2(.4) d["cmap"] = cm.Reds(.8) d["precl"] = cm.Purples(.9) return d[typ]
def threeColorScales(number_of_lines, start=0.2, stop=1.0): cm_subsection = np.linspace(start, stop, number_of_lines) colorsBlue = [cm.Blues(x) for x in cm_subsection] colorsRed = [cm.Reds(x) for x in cm_subsection] colorsGreen = [cm.Greens(x) for x in cm_subsection] allColors = [colorsBlue, colorsRed, colorsGreen] return allColors
def highlightBackProp(image, model2): #steering_angle = float(model.predict(image[None, :, :, :], batch_size=1)) # print(image.shape) #image = cv2.resize(image, (256, 256) ) oldimage = image #image = cv2.resize(image, (200, 66) ) # transpose if model is other way count, h, w, ch = model2.inputs[0].get_shape() ih, iw, ich = image.shape if h == ich and ch == ih: image = image.transpose() #print(image.shape) m1d = model2.predict(image[None, :, :, :], batch_size=1) #print(m1d.shape) m1d = np.squeeze(m1d, axis=0) m1d = np.squeeze(m1d, axis=2) #m1d = cv2.resize(image, (120, 160) ) #m1d=np.resize(m1d,(120,160)) #print(m1d.shape) #print(m1d) #plt.hist(m1d[::-1]) #plt.show() #print(m1d.max()) #print(m1d.min()) o2 = overlay = Image.fromarray(cm.Reds(m1d / m1d.max(), bytes=True)) #o2= o2.convert("RGB") #return o2 #plt.imshow(o2); #plt.show(); pixeldata = list(overlay.getdata()) for i, pixel in enumerate(pixeldata): if almostEquals(pixel[:3], (255, 255, 255)): pixeldata[i] = (255, 255, 255, 0) else: pixeldata[i] = (pixel[0], pixel[1], pixel[2], 128) overlay.putdata(pixeldata) #obig= cv2.resize(overlay, (320, 160) ) carimg = Image.fromarray(np.uint8(image)) #carimg = Image.fromarray(np.uint8(oldimage)) carimg = carimg.convert("RGBA") new_img2 = Image.alpha_composite(carimg, overlay) new_img2 = new_img2.convert("RGB") o2 = o2.convert("RGB") #plt.imshow(o2); #plt.show(); return np.array(new_img2)
def get_eth_config(): nodes = [4, 8, 16, 32] fpaths, tags, legends, colors = [], [], [], [] ar_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ar_eth_tags = [ 'AR-DPSGD-CPUCOMM-4ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-8ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-16ETH-SCRATCH', 'AR-DPSGD-CPUCOMM-32ETH-SCRATCH' ] ar_eth_legends = [ 'AR-SGD 4 nodes', 'AR-SGD 8 nodes', 'AR-SGD 16 nodes', 'AR-SGD 32 nodes' ] ar_eth_colors = [ cm.Reds(x) for x in np.linspace(0.3, 0.8, len(ar_eth_tags)) ] fpaths.append(ar_eth_fpath) tags.append(ar_eth_tags) legends.append(ar_eth_legends) colors.append(ar_eth_colors) ds_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ds_eth_tags = [ 'SDS-SGD-4ETH', 'SDS-SGD-8ETH', 'SDS-SGD-16ETH', 'SDS-SGD-32ETH' ] ds_eth_legends = [ 'D-PSGD 4 nodes', 'D-PSGD 8 nodes', 'D-PSGD 16 nodes', 'D-PSGD 32 nodes' ] ds_eth_colors = [ cm.Greens(x) for x in np.linspace(0.3, 0.8, len(ds_eth_tags)) ] fpaths.append(ds_eth_fpath) tags.append(ds_eth_tags) legends.append(ds_eth_legends) colors.append(ds_eth_colors) ps_eth_fpath = 'results_dir/out_files/{tag}out_r{r}_n{n}.csv' ps_eth_tags = [ 'PS-SGD-4ETH-CHORD', 'PS-SGD-8ETH-CHORD', 'PS-SGD-16ETH-CHORD', 'PS-SGD-32ETH-SCRATCH-CHORD' ] ps_eth_legends = [ 'SGP 4 nodes', 'SGP 8 nodes', 'SGP 16 nodes', 'SGP 32 nodes' ] ps_eth_colors = [ cm.Blues(x) for x in np.linspace(0.3, 0.8, len(ps_eth_tags)) ] fpaths.append(ps_eth_fpath) tags.append(ps_eth_tags) legends.append(ps_eth_legends) colors.append(ps_eth_colors) # return nodes, fpaths[::-1], tags[::-1], legends[::-1], colors[::-1] return nodes, fpaths, tags, legends, colors
def onclick(self, event): if event.inaxes == self.ax: self.xcoords.append(event.xdata) self.ycoords.append(event.ydata) xlim0, xlim1 = self.ax.get_xlim() if len(self.ycoords) == 2: # set values for horizontal lines self.horizontal_line1.set_ydata(self.ycoords[0]) self.horizontal_line2.set_ydata(self.ycoords[1]) # set text values with y values self.text1.set_text("{0:.2f}".format(self.ycoords[0])) self.text1.set_position((xlim0, self.ycoords[0])) self.text2.set_text("{0:.2f}".format(self.ycoords[1])) self.text2.set_position((xlim0, self.ycoords[1])) # fill between with axhspan self.hspan.set_xy([[0, self.ycoords[0]], [0, self.ycoords[1]], [1, self.ycoords[1]], [1, self.ycoords[0]]]) for i in range(len(self.mean)): prob_over_max_value = 1 - \ st.norm.cdf(max(self.ycoords), self.mean[i], self.confint[i]) prob_under_min_value = st.norm.cdf(min(self.ycoords), self.mean[i], self.confint[i]) between_prob = 1 - \ (prob_over_max_value + prob_under_min_value) if np.abs(between_prob < 0.1): between_prob = 0 if np.abs(prob_over_max_value < 0.001): prob_over_max_value = 0 if np.abs(prob_under_min_value < 0.001): prob_under_min_value = 0 # print('[{}] PUMaxV: {} POMinV: {} Between probabilities: {}'.format( # i, prob_over_max_value, prob_under_min_value, between_prob)) self.diff.append(round(between_prob, 3)) self.ax.bar(self.values, self.mean, yerr=[self.confint, self.confint], edgecolor='black', color=cm.Reds(tuple(self.diff))) self.fig.canvas.draw() # print(self.diff) # reset coordinates self.xcoords = [] self.ycoords = [] self.diff = []
def get_colors(color_c=3, color_step=100): cmap_colors = np.vstack(( cm.Oranges(np.linspace(0.4, 1, color_step)), cm.Reds(np.linspace(0.4, 1, color_step)), cm.Greys(np.linspace(0.4, 1, color_step)), cm.Purples(np.linspace(0.4, 1, color_step)), cm.Blues(np.linspace(0.4, 1, color_step)), cm.Greens(np.linspace(0.4, 1, color_step)), cm.pink(np.linspace(0.4, 1, color_step)), cm.copper(np.linspace(0.4, 1, color_step)), )) return cmap_colors[np.arange(color_c * color_step) % (color_step * 8)]
def to_heatmap(gcam, start_r, end_r, color='red'): if start_r != -1 and end_r != -1: gcam[0:start_r, ...] = 0 gcam[end_r:, ...] = 0 alpha = gcam[..., None] * PROB_WEIGHT alpha[alpha > 1.0] = 1.0 if color == 'red': cmap = cm.Reds(gcam)[..., :3] * 255.0 else: cmap = cm.Blues(gcam)[..., :3] * 255.0 cmap = cmap[..., ::-1] cmap = cmap.astype(np.float) return cmap, alpha
def initplot(genes): """ Starts a figure and initiates colors :param genes: :return: axis handle, colors for the genome values and colors for the lines """ cm_subsection = linspace(0, 1, len(genes[0]) + 2) colors = [cm.summer(x) for x in cm_subsection] colors2 = [cm.Reds(x) for x in cm_subsection] fig = plt.figure(figsize=(10, 15)) ax = fig.add_subplot(111) return ax, colors, colors2
def update_sensitivity_plot(fig, ax, sens, spec, title=''): """ update a ROC plot """ mem = 10000 sens = sens[max(0, len(sens) - mem):] spec = spec[max(0, len(spec) - mem):] ax.clear() ax.set_ylim((-0.05, 1.05)) ax.set_xlim((-0.05, 1.05)) ax.set_xlabel('1-specificity') ax.set_ylabel('sensitivity') ax.scatter(1 - np.array(spec), sens, c=cm.Reds(np.arange(0, 1.0, 1.0 / float(len(sens)))), linewidths=0.2) ax.plot([0, 1], [0, 1]) ax.set_title(title, size=16)
def calculate_on_target(ax, barcodes, expected, barcode_map=barcode_map): """Plots number of on target and off target barcodes as pie chart ax : matplotlib axis axis to plot on barcodes : Counter Counter object of barcode -> counts for each barcode counted expected : list list of barcodes (R01, R02..._ that are expected from this experiment barcode_map : dict dictionary barcode sequence -> human readable name """ total = 0 on_target = 0 off_target = 0 no_target = 0 expected_counts = [] off_target_counts = [] expected_names = [] off_target_names = [] for barcode, count in barcodes.items(): if barcode in barcode_map: if count > 10000: if barcode_map[barcode] in expected: on_target += count expected_counts.append(count) expected_names.append(barcode_map[barcode]) else: off_target += count off_target_counts.append(count) off_target_names.append(barcode_map[barcode]) else: no_target += count total += count expected_colors = cm.Blues(np.linspace(0, 1, len(expected_counts))) off_target_colors = cm.Reds(np.linspace(0, 1, len(off_target_counts) + 1)) patches, texts = ax.pie( expected_counts + off_target_counts + [no_target], labels=expected_names + off_target_names + ["No Barcode"], colors=np.concatenate((expected_colors, off_target_colors)), ) [text.set_fontsize(16) for text in texts]
def makeHeatMap(fname,wname,image,bins): f = open(fname) coords = np.array([[0,0]]) g = open(wname) weights = [] for weight in g: weight = weight.translate(None, '()[]') weight = weight.split(',')[1] weight = float(weight) weights.append(weight) i = 0 #print(weights) for line in f: #print(i) line = line.translate(None, '[]') point = line.split(',') point = map(float, point) point = map(abs,point) #print(genCircle(point,100).shape) coords = np.append(coords,genCircle(point,int(weights[i]*100000)),axis=0) i = i+1 coords = coords[1:] print(coords.shape) bg = imread(image) hmap, extent = heatmap(coords[:,0], coords[:,1], 1.5,bins) print(hmap.shape) #hmap = hmap[~np.all(hmap == 0, axis=1)] #hmap = hmap[hmap!=[0.0,0.0]] alphas = np.clip(Normalize(0, hmap.max(), clip=True)(hmap)*1.5, 0.0, 1.) colors = Normalize(0, hmap.max(), clip=True)(hmap) colors = cm.Reds(colors) colors[..., -1] = alphas fig, ax = plt.subplots(figsize=(24,24)) if "erangel" in image: ax.set_xlim(0, 4096); ax.set_ylim(0, 4096) else: ax.set_xlim(0, 1000); ax.set_ylim(0, 1000) ax.imshow(bg) ax.imshow(colors, extent=extent, origin='lower', cmap=cm.Reds, alpha=1.0) #plt.scatter(coords[:,0], coords[:,1]) plt.gca().invert_yaxis() plt.savefig("../Plots/" + fname[11:-3]+"jpg")
def draw_convex_combination_3d(points, cc_points, sides=None, color_z=True): fig = plt.figure() # To create a 3D plot a sublot with projection='3d' must be created. # For this to work required is the import of Axes3D: "from mpl_toolkits.mplot3d import Axes3D" ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') # TODO: Zadanie 4.3: Zaimplementuj rysowanie wykresu 3D dla cc_points. Możesz dodatkowo zaimplementować kolorowanie względem wartości na osi z. z_colours = [ cm.Reds((z + 1) / 2) for z in (cc_points[:, 2] - np.min(cc_points[:, 2])) / np.ptp(cc_points[:, 2]) ] ax.scatter(cc_points[:, 0], cc_points[:, 1], cc_points[:, 2], c=z_colours) # Drawing contour of the figure (with plt.plot). if sides is not None: draw_contour_3d(points, sides)
def _viz_transition_t(scenario: ExperimentScenario, example: Dict, t: int): action = index_batch_time(example, fwd_model.action_keys, b=t, t=0) s0 = index_batch_time_with_metadata(metadata, example, fwd_model.state_keys, b=t, t=0) s1 = index_batch_time_with_metadata(metadata, example, fwd_model.state_keys, b=t, t=1) if 'accept_probablity' in example: accept_probability_t = example['accept_probability'][t] color = cm.Reds(accept_probability_t) else: color = "#aa2222aa" scenario.plot_state_rviz(s0, label='', color='#ff0000ff') scenario.plot_state_rviz(s1, label='predicted', color=color) scenario.plot_action_rviz(s0, action, label='')
def __init__(self,data_pred,data_gt,colors,img,types,gif_name = "test.gif", plot_ = False, save = True): self.img = img self.xs_pred = data_pred[:,:,0] self.ys_pred = data_pred[:,:,1] self.xs_gt = data_gt[:,:,0] self.ys_gt = data_gt[:,:,1] self.types = types self.nb_agents = self.xs_pred.shape[0] self.margin = 1 self.nb_frames = self.xs_pred.shape[1] self.gif_name = gif_name self.plot_ = plot_ self.save = save self.fps = 1 self.colors = colors self.lin_size = 100 lin = np.linspace(0.6, 0.8, self.lin_size) self.color_dict = { "bicycle":cm.Blues(lin), "pedestrian":cm.Reds(lin), "car":cm.Greens(lin), "skate":cm.Greys(lin), "cart":cm.Purples(lin), "bus":cm.Oranges(lin) } self.colors = [self.color_dict[type_][np.random.randint(self.lin_size)] for type_ in self.types] self.history = 4 self.get_plots()
def get_transformer_config(): nodes = [8, 8] fpaths, tags, legends, colors = [], [], [], [] fpath = 'results_dir/transformer_{tag}_test.out' ps_tags = ['ps_sm', 'ps'] ps_legends = ['SGP (25K batch)', 'SGP (400K batch)'] ps_colors = [cm.Blues(x) for x in np.linspace(0.3, 0.8, len(ps_tags))] fpaths.append(fpath) tags.append(ps_tags) legends.append(ps_legends) colors.append(ps_colors) fpath = 'results_dir/transformer_{tag}_test.out' ar_tags = ['ar_sm', 'ar'] ar_legends = ['SGD (25K batch)', 'SGD (400K batch)'] ar_colors = [cm.Reds(x) for x in np.linspace(0.3, 0.8, len(ar_tags))] fpaths.append(fpath) tags.append(ar_tags) legends.append(ar_legends) colors.append(ar_colors) return nodes, fpaths, tags, legends, colors
def log_predictions( self, pred: np.ndarray, clusterings: Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]] ) -> None: type_count = pred.shape[-1] new_size = self.preprocessed_screen.shape[:2] final_pred_size = (new_size[0] * int(type_count**.5), new_size[1] * (type_count // int(type_count**.5))) final_pred = np.zeros((*final_pred_size, 3), dtype=np.uint8) original_pred = np.uint8(cm.viridis(pred)[:, :, :, :3] * 255) for type in range(type_count): pred = original_pred[:, :, type, :] if clusterings is not None or self.prediction_overlay_factor > 0: prev_size = pred.shape[:2] pred = Image.fromarray(pred) pred = pred.resize((new_size[1], new_size[0])) pred = Image.blend(pred, Image.fromarray(self.preprocessed_screen), self.prediction_overlay_factor) pred = np.array(pred) if clusterings is not None: clustering = tuple(x[type] for x in clusterings) cluster_colors = cm.Reds( np.linspace(0, 1, len(clustering[2])))[:, :3] * 255 for cluster in zip(*clustering[:2]): cl_ind = np.where(clustering[2] == cluster[1])[0] if len(cl_ind) > 0: y, x = tuple(cluster[0][:2] * new_size // prev_size) pred[y:y + self.cluster_color_size, x:x + self.cluster_color_size] \ = cluster_colors[cl_ind[0]] type_x = type // (final_pred_size[1] // new_size[1]) type_y = type % (final_pred_size[1] // new_size[1]) final_pred[type_x * new_size[0]:(type_x + 1) * new_size[0], type_y * new_size[1]:(type_y + 1) * new_size[1]] = pred self.log_image('Predictions', final_pred)
def __init__(self, ax, mean, confint, std, values, clicklim=0.05): self.fig = ax.figure self.diff = [] self.values = values self.ax = ax self.mean = mean self.confint = confint self.std = std self.ycoords = [] self.xcoords = [] self.clicklim = clicklim self.horizontal_line1 = ax.axhline(y=0.4, color='black', alpha=0.5) self.horizontal_line2 = ax.axhline(y=0.7, color='black', alpha=0.5) self.hspan = ax.axhspan(2, 4, facecolor='gray', alpha=0.3) self.text1 = ax.text(0, 0.4, "") self.text2 = ax.text(0, 0.7, "") self.ax.bar(self.values, self.mean, yerr=self.confint, edgecolor='black', color=cm.Reds(tuple(self.confint / 10000))) self.fig.canvas.mpl_connect('button_press_event', self.onclick)
defocus_zernike[0, 1] = 1.0 defocus_actuators = zernike_fit.fit_zernike_wave_to_actuators( defocus_zernike, plot=True, cmap='Reds')[:, 0] # Loop over the strength of defocus to see what is the optimum value rms_before, rms_after = [], [] diversities, rms_div = [], [] mean_peak_foc = [] # Noise RMS N_cases = 30 noiseSNR = np.array([500, 250, 100]) N_noise = noiseSNR.shape[0] rms_after_noisy = np.zeros((N_noise, N_cases)) rms_div_noisy = np.zeros((N_noise, N_cases)) colors = cm.Reds(np.linspace(0.5, 0.75, N_noise)) # beta = np.linspace(0.30, 4.0, N_cases) beta = np.linspace(0.25, 7.0, N_cases) N_foc = beta.shape[0] # fig, axes = plt.subplots(N_foc, 3) for k_noise in range(N_noise): for i_beta, b in enumerate(beta): print("\nBeta: %.2f" % b) # Update the Diversity Map on the actuator model so that it matches Defocus diversity_defocus = b * defocus_actuators / (2 * np.pi) PSF_actuators.define_diversity(diversity_defocus) # plt.figure()
# # diff_foc = p_foc_anam - p_foc # # fake_psf_foc, s = PSF_zernike.compute_PSF(x + x_coef + defocus_zernike) # # fake_diff_foc = fake_psf_foc - p_foc # # foc_diff = (fake_psf_foc - p_foc_anam).flatten() # # total = np.concatenate([nom_diff, 0.1*foc_diff]) # print(total.shape) return nom_diff # ratios = [1.05, 1.10, 1.25] ratios = [1.05] markers = ['^', 'v', 'd', 'o'] colors = cm.Reds(np.linspace(0.5, 1.0, 3)) plt.figure() for j, r in enumerate(ratios): # (1) We define the anamorphic PSF model anamorphic_ratio = r zernike_matrices_anam = psf.zernike_matrix(N_levels=N_levels, rho_aper=RHO_APER, rho_obsc=RHO_OBSC, N_PIX=N_PIX, radial_oversize=1.0, anamorphic_ratio=anamorphic_ratio) zernike_matrix_anam, pupil_mask_zernike_anam, flat_zernike_anam = zernike_matrices_anam zernike_matrices_anam = [zernike_matrix_anam, pupil_mask_zernike_anam, flat_zernike_anam] PSF_zernike_anam = psf.PointSpreadFunction(matrices=zernike_matrices_anam, N_pix=N_PIX, crop_pix=pix, diversity_coef=np.zeros(zernike_matrix.shape[-1])) PSF_zernike_anam.define_diversity(defocus_zernike) x0 = np.random.uniform(low=-0.1, high=0.1, size=N_zern)