def plot_results(dists): for i, d in enumerate(dists): ax = plt.subplot(3,3,(4*i)+1) N, bins, patches = plt.hist(d.data, color="b",ec="k", bins=30, \ range=tuple(d.lims), normed=True, \ edgecolor="k", histtype='bar',linewidth=1.) fracs = N.astype(float)/N.max() norm = Normalize(-.2* fracs.max(), 1.5 * fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.gray_r(norm(thisfrac)) thispatch.set_facecolor(color) thispatch.set_edgecolor("w") x = np.linspace(d.data.min(), d.data.max(), 100) ylim = ax.get_ylim() plt.plot(x, d.best.pdf(x), "-r", lw=1.5, alpha=0.7) ax.set_ylim(ylim) plt.axvline(d.best.MAPP, c="r", ls="--", lw=1.5) plt.tick_params(labelright=True, labelleft=False, labelsize=10) plt.xlim(d.lims) plt.locator_params(axis='x',nbins=10) if i < 2: plt.setp(ax.get_xticklabels(), visible=False) else: plt.xlabel(r"[$\mathregular{\alpha}$ / Fe]") plt.minorticks_on() def hist2D(dist1, dist2): """ Plot distribution and confidence contours. """ X, Y = np.mgrid[dist1.lims[0] : dist1.lims[1] : 20j, dist2.lims[0] : dist2.lims[1] : 20j] extent = [dist1.lims[0], dist1.lims[1], dist2.lims[0], dist2.lims[1]] positions = np.vstack([X.ravel(), Y.ravel()]) values = np.vstack([dist1.data, dist2.data]) kernel = stats.gaussian_kde(values) Z = np.reshape(kernel(positions).T, X.shape) ax.imshow(np.rot90(Z), cmap="gray_r", extent=extent, aspect="auto", interpolation="spline16") plt.axvline(dist1.best.MAPP, c="r", ls="--", lw=1.5) plt.axhline(dist2.best.MAPP, c="r", ls="--", lw=1.5) plt.tick_params(labelsize=10) ax.minorticks_on() plt.locator_params(axis='x',nbins=10) return ax = plt.subplot(3,3,4) hist2D(dists[0], dists[1]) plt.setp(ax.get_xticklabels(), visible=False) plt.ylabel("[Z/H]") plt.xlim(dists[0].lims) plt.ylim(dists[1].lims) ax = plt.subplot(3,3,7) hist2D(dists[0], dists[2]) plt.ylabel(r"[$\mathregular{\alpha}$ / Fe]") plt.xlabel("log Age (yr)") plt.xlim(dists[0].lims) plt.ylim(dists[2].lims) ax = plt.subplot(3,3,8) plt.xlabel("[Z/H]") hist2D(dists[1], dists[2]) plt.xlim(dists[1].lims) plt.ylim(dists[2].lims) return
def plot_graph(weights, display=True, output_file=None, output_format="pdf"): """Plot a two dimensional array of weights. Parameters ---------- display: boolean, optional show the plot of the graph output_file: str or path, optional path to file to save graph in, does not save per default output_format: "pdf", "png" or "jpg" """ cues = weights.index outcomes = weights.columns minimum = np.min(weights.values) maximum = np.max(weights.values) # colour code edge weights normalization = colors.Normalize(vmin=minimum, vmax=maximum) scale = cm.ScalarMappable(norm=normalization, cmap=cm.seismic) colours = scale.to_rgba(weights) colours = np.ndarray.flatten(colours).reshape(weights.size, -1) # structure graph bipartite_graph = nx.Graph() bipartite_graph.add_nodes_from(cues, bipartite=0) bipartite_graph.add_nodes_from(outcomes, bipartite=1) bipartite_graph.add_edges_from([(cue, outcome) for cue in cues for outcome in outcomes]) left, right = nx.bipartite.sets(bipartite_graph) # make positions for each node # (multiply by len() of other partition to center) positions = dict() for idx, node in enumerate(left): positions[node] = (1, len(outcomes) * idx) for idx, node in enumerate(right): positions[node] = (2, len(cues) * idx) # make dictionary with labels labels = dict() for idx, cue in enumerate(chain(cues, outcomes)): labels[cue] = cue # shade nodes depending on activation level # (cues have fixed activation) activations = weights.sum(0) activations_normalized = softmax(activations) alphas = [0.5] * len(cues) + activations_normalized gray_values = cm.gray_r(alphas) # draw nx.draw(bipartite_graph, pos=positions, edge_color=colours, labels=labels, node_size=400, node_shape="o", node_color=gray_values) # display and save if display: plt.show() if output_file: plt.savefig(output_file, format=output_format)
#Read morphology X = np.array(Line[1:], dtype="float64") Z = np.array((Lines[j + 1].strip().split(" "))[1:], dtype="float64") #Read concentrations X2 = np.array((Lines2[j].strip().split(" "))[1:], dtype="float64") N = np.array((Lines2[j + 1].strip().split(" "))[1:], dtype="float64") if (j == 1): CliffPositionXOld = X[0] TimeOld = 0 ax1.plot(X, Z, '-', lw=1.5, color=cm.gray_r((Time + 1000) / (EndTime + 1000))) PlotTime += PlotInterval else: CliffPositionX = X[0] Times.append(Time) RR = (CliffPositionXOld - CliffPositionX) / (TimeOld - Time) RetreatRate.append(RR) # Platform gradient, measure bewteen 0.5 and -0.9m elevation TopInd = np.argmin(np.abs(Z - 0.5)) BottomInd = np.argmin(np.abs(Z - (-0.9))) Grad = np.abs((Z[TopInd] - Z[BottomInd]) / (X[TopInd] - X[BottomInd])) PlatformGradient.append(Grad) if (Time == PlotTime):
def _checker_image(self): pattern = (np.indices(self.get_shape()) // 8).sum(0) % 2 return Image.fromarray(cm.gray_r(pattern / 2.0, bytes=True))
def plot_CD(layer_thickness, thermal_conductivity, icb_heatflux, csb_heatflux, saveOn, figAspect=0.75): w, h = plt.figaspect(figAspect) # fig, (ax1,ax2,ax3) = plt.subplots(3,1,figsize=(1.25*w,1.25*h),sharex=True) fig = plt.figure(constrained_layout=True, figsize=(1.25 * w, 2 * h)) spec = gridspec.GridSpec(ncols=1, nrows=3, figure=fig) ax1 = fig.add_subplot(spec[0, 0]) ax2 = ax1.twinx() ax3 = fig.add_subplot(spec[1, 0], sharex=ax1) n = layer_thickness.size*thermal_conductivity.size \ *icb_heatflux.size*csb_heatflux.size if n != 1: fig_label = [r'high $Le$', r'low $Le$'] start = 0.2 stop = 0.5 cm_subsection = np.linspace(start, stop, n) colors = [cm.gray_r(x) for x in cm_subsection] # Load data k = 0 for w, x, y, z in [(w, x, y, z) for w in layer_thickness for x in icb_heatflux for y in csb_heatflux for z in thermal_conductivity]: foldername, filename = get_outputDir(w, x, y, z) inputDir = "results/{}/{}/".format(foldername, filename) try: inputs, outputs, profiles = readdata(inputDir) except: print('{} does not exist'.format(inputDir)) return # Calculate bulk modulus from PREM bulk_modulus = premvp(profiles.r)**2 * premdensity(profiles.r) # Calculate vp using slurry density and PREM bulk modulus vp_slurry = np.sqrt(bulk_modulus / profiles.density) # Calculate FVW P wave speed (Ohtaki et al. 2015, fig 11a) x = profiles.r / earth_radius vp_fvw = 3.3 * x[0] - 3.3 * x + 10.33 max_diff = np.max((vp_fvw - vp_slurry * 1e-3) / vp_fvw * 100) print('Maximum difference with Ohtaki et al. (2015) is {:.2f}%'.format( max_diff)) max_diff = np.max( (premvp(profiles.r) - vp_slurry) / premvp(profiles.r) * 100) print('Maximum difference with PREM is {:.2f}%'.format(max_diff)) print('Density on slurry side of ICB is {:.2f}'.format( profiles.density[0])) density_jump = profiles.density[0] - profiles.density.iloc[-1] print('Density jump is {:.2f}'.format(density_jump)) rho_bod = density_solidFe - profiles.density[0] print('Delta rho bod is {:.2f}'.format(rho_bod)) rho_mod = rho_bod + density_jump print('Delta rho mod is {:.2f}'.format(rho_mod)) # Plot P wave speed if n == 1: ax3.plot(profiles.r * 1e-3, vp_slurry * 1e-3, color='darkgrey', lw=2, label='slurry density') #(km/s) ax3.vlines(profiles.r[0] * 1e-3, vp_slurry[0] * 1e-3, 10.4, color='darkgrey', lw=2) else: ax3.plot(profiles.r * 1e-3, vp_slurry * 1e-3, color=colors[k], lw=2, label=fig_label[k]) #(km/s) ax3.vlines(profiles.r[0] * 1e-3, vp_slurry[0] * 1e-3, 10.4, color=colors[k], lw=2) # Check density # ax3.plot(profiles.r*1e-3,premdensity(profiles.r),'k--') # ax3.plot(profiles.r*1e-3,profiles.density) k += 1 # Plot temperature and composition ax1.plot(profiles.r * 1e-3, profiles.temp, lw=2, color='red', label='temperature') (mass_conc_O, acore) = getcsbmassoxygen(inputs.oxygen_bulk) acore = float(acore) ax2.plot(profiles.r * 1e-3, profiles.oxygen * acore / aO * 100, lw=2, color='blue', label='oxygen') # Plot FVW, PREM and AK135 ax3.plot(profiles.r * 1e-3, vp_fvw, color='black', lw=2, ls=':', label='Ohtaki et al. (2015)') ax3.vlines(profiles.r[0] * 1e-3, vp_fvw[0], 10.4, color='black', ls=':', lw=2) ax3.plot(profiles.r * 1e-3, premvp(profiles.r) * 1e-3, color='k', ls='--', label='PREM') ax3.vlines(profiles.r[0] * 1e-3, premvp(profiles.r[0]) * 1e-3, 10.4, 'k', linestyle='--') # ax3.plot(radius_ak135*1e-3,vp_ak135*1e-3,'k',label='ak135') # ax3.vlines(radius_ak135[0]*1e-3,vp_ak135[0]*1e-3,10.4, 'k') ax3.legend(fontsize=11.5, loc='upper right') ax1.set(ylabel="Temperature (K)") ax1.spines["right"].set_edgecolor('red') ax1.spines["right"].set_edgecolor('blue') ax1.yaxis.label.set_color('red') ax2.set(ylabel="Oxygen (mol.%)") ax2.spines["left"].set_edgecolor('red') ax2.spines["right"].set_edgecolor('blue') ax2.yaxis.label.set_color('blue') ax2.tick_params(axis='y', colors='blue') ax1.tick_params(axis='y', which='both', colors='red') ax3.set(xlabel="Radius (km)") ax3.set(ylabel="P wave speed (km/s)") ax3.set_xlim([1200, profiles.r.iloc[-1] * 1e-3]) ax3.set_ylim([10.25, 10.4]) major_xticks = np.arange(1200, 1370, 20) minor_xticks = np.arange(1200, 1370, 5) ax1.set_xticks(major_xticks) ax1.set_xticks(minor_xticks, minor=True) ax2.set_xticks(major_xticks) ax2.set_xticks(minor_xticks, minor=True) ax3.set_xticks(major_xticks) ax3.set_xticks(minor_xticks, minor=True) major_yticks = np.arange(5500, 5751, 100) minor_yticks = np.arange(5500, 5751, 20) ax1.set_yticks(major_yticks) ax1.set_yticks(minor_yticks, minor=True) ax1.grid(which='minor', alpha=0.2) ax1.grid(which='major', alpha=0.5) ax1.tick_params(which='major', length=7) ax1.tick_params(which='minor', length=3.5) # major_yticks = np.arange(6.5,8.1,0.5) # minor_yticks = np.arange(6.5,8.1,0.1) # ax2.set_yticks(major_yticks) # ax2.set_yticks(minor_yticks, minor=True) # ax2.grid(which='minor', alpha=0.2) # ax2.grid(which='major', alpha=0.5) # ax2.tick_params(which='major',length = 7) # ax2.tick_params(which='minor',length = 3.5) major_yticks = np.arange(10.25, 10.4, 0.05) minor_yticks = np.arange(10.25, 10.4, 0.01) ax3.set_yticks(major_yticks) ax3.set_yticks(minor_yticks, minor=True) ax3.grid(which='minor', alpha=0.2) ax3.grid(which='major', alpha=0.5) ax3.tick_params(which='major', length=7) ax3.tick_params(which='minor', length=3.5) if saveOn == 1: saveDir = 'figures/seismic/' if not os.path.exists(saveDir + foldername): os.makedirs(saveDir + foldername) fig.savefig(saveDir + foldername + "/" + filename + "_CD.pdf", format='pdf', dpi=200, bbox_inches='tight') fig.savefig(saveDir + foldername + "/" + filename + "_CD.png", format='png', dpi=200, bbox_inches='tight') print('Figure saved as {}'.format(saveDir + foldername + "/" + filename + "_CD.pdf")) plt.show() return profiles.r, vp_slurry, profiles.density, vp_fvw
def plot_seismic_dark(layer_thickness, thermal_conductivity, icb_heatflux, csb_heatflux, saveOn, figAspect=0.75): w, h = plt.figaspect(figAspect) fig, ax = plt.subplots(1, 1, figsize=(1.25 * w, 1.25 * h)) n = layer_thickness.size*thermal_conductivity.size \ *icb_heatflux.size*csb_heatflux.size if n != 1: fig_label = [r'high $Le$', r'low $Le$'] start = 0.2 stop = 0.5 cm_subsection = np.linspace(start, stop, n) colors = [cm.gray_r(x) for x in cm_subsection] # Load data k = 0 for w, x, y, z in [(w, x, y, z) for w in layer_thickness for x in icb_heatflux for y in csb_heatflux for z in thermal_conductivity]: foldername, filename = get_outputDir(w, x, y, z) inputDir = "results/{}/{}/".format(foldername, filename) try: inputs, outputs, profiles = readdata(inputDir) except: print('{} does not exist'.format(inputDir)) return # Calculate bulk modulus from PREM bulk_modulus = premvp(profiles.r)**2 * premdensity(profiles.r) # Calculate vp using slurry density and PREM bulk modulus vp_slurry = np.sqrt(bulk_modulus / profiles.density) # Calculate FVW P wave speed (Ohtaki et al. 2015, fig 11a) x = profiles.r / earth_radius vp_fvw = 3.3 * x[0] - 3.3 * x + 10.33 max_diff = np.max((vp_fvw - vp_slurry * 1e-3) / vp_fvw * 100) print('Maximum difference with Ohtaki et al. (2015) is {:.2f}%'.format( max_diff)) max_diff = np.max( (premvp(profiles.r) - vp_slurry) / premvp(profiles.r) * 100) print('Maximum difference with PREM is {:.2f}%'.format(max_diff)) print('Density on slurry side of ICB is {:.2f}'.format( profiles.density[0])) density_jump = profiles.density[0] - profiles.density.iloc[-1] print('Density jump is {:.2f}'.format(density_jump)) rho_bod = density_solidFe - profiles.density[0] print('Delta rho bod is {:.2f}'.format(rho_bod)) rho_mod = rho_bod + density_jump print('Delta rho mod is {:.2f}'.format(rho_mod)) # Plot P wave speed if n == 1: ax.plot(profiles.r * 1e-3, vp_slurry * 1e-3, color='darkgrey', lw=2, label='slurry') #(km/s) ax.vlines(profiles.r[0] * 1e-3, vp_slurry[0] * 1e-3, 10.4, color='darkgrey', lw=2) else: ax.plot(profiles.r * 1e-3, vp_slurry * 1e-3, color=colors[k], lw=2, label=fig_label[k]) #(km/s) ax.vlines(profiles.r[0] * 1e-3, vp_slurry[0] * 1e-3, 10.4, color=colors[k], lw=2) # Check density # ax1.plot(profiles.r*1e-3,premdensity(profiles.r),'k--') # ax1.plot(profiles.r*1e-3,profiles.density) k += 1 # Look up AK135 radius_ak135 = ak135radius() vp_ak135 = ak135vp(radius_ak135) ax.plot(profiles.r * 1e-3, vp_fvw, color='blue', lw=2, ls=':', label='Ohtaki et al. (2015)') ax.vlines(profiles.r[0] * 1e-3, vp_fvw[0], 10.4, color='blue', lw=2, ls=':') ax.plot(profiles.r * 1e-3, premvp(profiles.r) * 1e-3, color='white', ls='--', label='PREM') ax.vlines(profiles.r[0] * 1e-3, premvp(profiles.r[0]) * 1e-3, 10.4, 'white', linestyle='--') ax.plot(radius_ak135 * 1e-3, vp_ak135 * 1e-3, 'white', label='ak135') ax.vlines(radius_ak135[0] * 1e-3, vp_ak135[0] * 1e-3, 10.4, 'white') ax.legend(fontsize=11.5) ax.set(xlabel="Radius (km)") ax.set(ylabel="P wave speed (km/s)") ax.set_xlim([1200, profiles.r.iloc[-1] * 1e-3]) ax.set_ylim([10.1, 10.4]) plt.yticks(np.arange(10.1, 10.41, 0.1)) if saveOn == 1: saveDir = 'figures/seismic/' if not os.path.exists(saveDir + foldername): os.makedirs(saveDir + foldername) fig.savefig(saveDir + foldername + "/" + filename + "_dark.pdf", format='pdf', dpi=200, bbox_inches='tight') fig.savefig(saveDir + foldername + "/" + filename + "_dark.png", format='png', dpi=200, bbox_inches='tight') print('Figure saved as {}'.format(saveDir + foldername + "/" + filename + ".pdf")) plt.show() return profiles.r, vp_slurry, profiles.density
def main(): alpha21 = '-' + IUPAC.protein.letters parser = argparse.ArgumentParser(description='Visualize Potts Models') parser.add_argument('bimarg') parser.add_argument('couplings') parser.add_argument('-alphamap', help='map from 21 letters to alpha') parser.add_argument('-unimarg21', help='21 letter univariate marginals') parser.add_argument('-contactfreq', help='contact frequency file') parser.add_argument('-contactmode', choices=['split', 'overlay', 'splitoverlay'], default='overlay', help='how to draw contact map') parser.add_argument('-score', default='fbwsqrt', choices=['fb', 'fbw', 'fbwsqrt', 'DI', 'MI', 'Xij']) parser.add_argument('-gauge', default='skip', choices=['skip', 'nofield', '0', 'w', 'wsqrt']) parser.add_argument('-alpha', default=alpha21) parser.add_argument('-annotimg', help='annotation image') parser.add_argument('-title', help='Figure title') parser.add_argument('-grid', type=int, default=10, help='grid spacing') parser.add_argument('-cnsrv', help='show conservation score') parser.add_argument('-Xijseq', help='seq ') parser.add_argument('-deltaXijseq', help='seq ') parser.add_argument('-pcN', help='small jeffreys pseudocount to add') args = parser.parse_args(sys.argv[1:]) alpha = args.alpha alpha21 = '-' + IUPAC.protein.letters ff = np.load(args.bimarg) J = np.load(args.couplings) if args.pcN: N = float(args.pcN) ff = mutation_pc(ff, N) unimarg = getUnimarg(ff) L, q = getLq(J) if args.gauge == 'nofield': h, J = changeGauge.fieldlessEven(zeros((L, q)), J) elif args.gauge == '0': h, J = changeGauge.zeroGauge(zeros((L, q)), J) elif args.gauge == 'w': h, J = changeGauge.zeroGauge(zeros((L, q)), J, weights=ff) elif args.gauge == 'wsqrt': h, J = changeGauge.zeroGauge(zeros((L, q)), J, weights=np.sqrt(ff)) else: h = zeros((L, q)) if args.deltaXijseq or args.Xijseq: Xij, Xijab = getXij(J, ff) if args.deltaXijseq: if args.Xijseq: raise ValueError("deltaXijseq, Xijseq are mutually exclusive") seq = args.deltaXijseq Xijab = Xijab - Xij else: seq = args.Xijseq seq = np.array([alpha.index(c) for c in seq], dtype='u4') pottsScore = np.array([ Xijab[n, q * seq[i] + seq[j]] for n, (i, j) in enumerate( (i, j) for i in range(L - 1) for j in range(i + 1, L)) ]) elif args.score == 'fb': h0, J0 = changeGauge.zeroGauge(h, J) pottsScore = sqrt(sum(J0**2, axis=1)) elif args.score == 'fbw': w = ff hw, Jw = changeGauge.zeroGauge(zeros((L, q)), J, weights=w) pottsScore = sqrt(sum((Jw * w)**2, axis=1)) elif args.score == 'fbwsqrt': w = sqrt(ff) hw, Jw = changeGauge.zeroGauge(zeros((L, q)), J, weights=w) pottsScore = sqrt(sum((Jw * w)**2, axis=1)) elif args.score == 'Xij': C = ff - indepF(ff) X = -np.sum(C * J, axis=1) pottsScore = X elif args.score == 'MI': pottsScore = np.sum(rel_entr(ff, indepF(ff)), axis=-1) else: raise Exception("Not yet implemented") if args.alphamap: unimarg21 = np.load(args.unimarg21) with open(args.alphamap) as f: alphamap = [l.split()[1:] for l in f.readlines()] # replace "junk" entry in alpha map with '*' alphamap_color = [] for l, a in enumerate(alphamap): clet = [] for g in a: if g == '*': clet.append([]) continue linds = [alpha21.index(c) for c in g] f = array([unimarg21[l, i] for i in linds]) let_dat = zip(g, f / sum(f)) let_dat.sort(key=lambda x: x[1], reverse=True) clet.append(let_dat) alphamap_color.append(clet) else: alphamap_color = [[[(c, 1.0)] for c in alpha] for i in range(L)] ss = 0.4 contactfig = plt.figure(figsize=(11, 10)) xscale = 10.0 / 11.0 yscale = 10.0 / 10.0 main_ax = plt.axes( (0.01 * xscale, 0.1 * yscale, 0.89 * xscale, 0.89 * yscale), zorder=3) cbar_ax = plt.axes((10.05 / 11, 0.1 * yscale, 0.3 / 11, 0.89 * yscale), zorder=3) if args.annotimg: try: ssim = np.load(args.annotimg) except ValueError: from PIL import Image ssim = np.array(Image.open(args.annotimg)) ax = plt.axes( (0.01 * xscale, 0.02 * yscale, 0.89 * xscale, 0.08 * yscale), sharex=main_ax) ax.set_axis_off() ax.imshow(ssim, extent=(-0.5, L - 0.5, 0, 16), interpolation='bicubic', aspect='auto') ax = plt.axes( (0.9 * xscale, 0.1 * yscale, 0.08 * xscale, 0.89 * yscale), sharey=main_ax) ax.set_axis_off() ax.imshow(ssim.transpose((1, 0, 2))[::-1, :, :], extent=(0, 16, -0.5, L - 0.5), interpolation='bicubic', aspect='auto') if args.contactfreq and args.contactmode == 'overlay': cont = getM(np.load(args.contactfreq)) # assume grayscale [0,1] cont = cm.gray_r(cont * 0.2) main_ax.imshow(cont, origin='lower', extent=(+o, L + o, +o, L + o), interpolation='nearest') scores = getM(pottsScore) img = main_ax.imshow(scores, origin='lower', cmap=alphared, extent=(+o, L + o, +o, L + o), interpolation='nearest') cbar = contactfig.colorbar(img, cax=cbar_ax) cbar = DraggableColorbar(cbar, img) cbar.connect() elif args.contactfreq and args.contactmode == 'split': lotri = ones((L, L), dtype=bool) lotri[triu_indices(L, k=1)] = False hitri = zeros((L, L), dtype=bool) hitri[triu_indices(L, k=1)] = True upper = getM(pottsScore) upper[hitri] = nan img = main_ax.imshow(upper, origin='lower', cmap='Blues', extent=(+o, L + o, +o, L + o), interpolation='nearest') cbar = contactfig.colorbar(img, cax=cbar_ax) cbar = DraggableColorbar(cbar, img) cbar.connect() lower = getM(np.load(args.contactfreq)) lower[lotri] = nan main_ax.imshow(lower, origin='lower', cmap='Reds', extent=(+o, L + o, +o, L + o), interpolation='nearest') if args.contactfreq and args.contactmode == 'splitoverlay': lotri = ones((L, L), dtype=bool) lotri[triu_indices(L, k=1)] = False hitri = zeros((L, L), dtype=bool) hitri[triu_indices(L, k=1)] = True cont = getM(np.load(args.contactfreq)) cont = cm.gray_r(cont * 0.2) main_ax.imshow(cont, origin='lower', extent=(+o, L + o, +o, L + o), interpolation='nearest') upper = getM(pottsScore) upper[hitri] = nan img = main_ax.imshow(upper, origin='lower', cmap=alphared, extent=(+o, L + o, +o, L + o), interpolation='nearest') cbar = contactfig.colorbar(img, cax=cbar_ax) cbar = DraggableColorbar(cbar, img) cbar.connect() else: img = main_ax.imshow(getM(pottsScore), origin='lower', cmap='gray_r', extent=(+o, L + o, +o, L + o), interpolation='nearest') cbar = contactfig.colorbar(img, cax=cbar_ax) cbar = DraggableColorbar(cbar, img) cbar.connect() if args.title: plt.title(args.title) if args.grid: main_ax.set_xticks(np.arange(0, L, 10)) main_ax.set_yticks(np.arange(0, L, 10)) main_ax.grid(color='black', linestyle=':', linewidth=0.2) gridfig_size = tuple(0.2 * x for x in (6 + q, 6 + q)) margfig = plt.figure(figsize=gridfig_size, facecolor='white') margax = plt.axes([0, 0, 1, 1]) Cfig = plt.figure(figsize=gridfig_size, facecolor='white') Cax = plt.axes([0, 0, 1, 1]) Jfig = plt.figure(figsize=gridfig_size, facecolor='white') Jax = plt.axes([0, 0, 1, 1]) ijpicker = PositionPicker(contactfig, (margax, Cax, Jax), alphamap_color, J, h, ff, pottsScore) plt.show()
def drawMarg(alphacolor, q, i, j, marg, J, hi, hj, score, margax, Cax, Jax): graytext = lambda x: { 'text': "{:.2f}".format(x), 'color': cm.gray_r(fnorm(x)) } bwrtext = lambda x: {'text': "{:.2f}".format(x), 'color': cm.bwr(fnorm(x))} rwbtext = lambda x: { 'text': "{:.2f}".format(x), 'color': cm.bwr_r(fnorm(x)) } mapi = alphacolor[i] mapj = alphacolor[j] for ax in (margax, Cax, Jax): ax.set_axis_off() ax.set_xlim(0, 6 + q) ax.set_ylim(0, 1 * (q + 5)) fnorm = Normalize(0, 0.1, clip=True) drawGrid(margax, 3, 1, 1, q, q, [[graytext(x) for x in r] for r in marg], mapi, mapj, '({}, {}) Bimarg'.format(i, j), list(map(graytext, sum(marg, axis=1))), list(map(graytext, sum(marg, axis=0))), labeltext=alphatext) fnorm = Normalize(-1, 1.0, clip=True) C = marg - outer(sum(marg, axis=1), sum(marg, axis=0)) Cmax = np.max(np.abs(C)) drawGrid(Cax, 3, 1, 1, q, q, [[rwbtext(x) for x in r] for r in C / Cmax], mapi, mapj, '({}, {}) C * {}'.format(i, j, str(Cmax)), None, None, labeltext=alphatext) fnorm = Normalize(-1, 1.0, clip=True) drawGrid(Jax, 3, 1, 1, q, q, [[bwrtext(x) for x in r] for r in J], mapi, mapj, '({}, {}) J score={:.2f}'.format(i, j, score), list(map(bwrtext, hi)), list(map(bwrtext, hj)), labeltext=alphatext)
metal = Dist(metal_data, [-2.25, 0.90]) alpha_data = np.loadtxt("Chain_0/alpha_dist.txt") alpha = Dist(alpha_data, [-0.3, 0.5]) dists = [ages, metal, alpha] log, summary = [r"{0:28s}".format(spec)], [] for i, d in enumerate(dists): weights = np.ones_like(d.data)/len(d.data) ax = plt.subplot(3,3,(4*i)+1) # plt.tick_params(labelsize=10) N, bins, patches = plt.hist(d.data, color="b",ec="k", bins=30, range=tuple(lims[i]), normed=True, edgecolor="k", histtype='bar',linewidth=1.) fracs = N.astype(float)/N.max() norm = Normalize(-.2* fracs.max(), 1.5 * fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.gray_r(norm(thisfrac)) thispatch.set_facecolor(color) thispatch.set_edgecolor("w") x = np.linspace(d.data.min(), d.data.max(), 100) tot = np.zeros_like(x) # for m,w,c in zip(d.gmm.best.means_, d.gmm.best.weights_, # d.gmm.best.covars_): # y = w * normpdf(x, m, np.sqrt(c))[0] # ax.plot(x, y, "--b") # tot += y # ax.plot(x,tot, "-b", lw=2) # pdf = np.exp(logprob) # pdf_individual = responsibilities * pdf[:, np.newaxis] # print pdf_individual ylim = ax.get_ylim() plt.plot(x, d.best.pdf(x), "-r", label="AD = {0:.1f}".format(
def plot(chain, ages, metal, alpha): dists = [ages, metal, alpha] log, summary = [r"{0:28s}".format(spec)], [] lims = [[9 + np.log10(1.), 9 + np.log10(15.)], [-2.25, 0.90], [-0.3, 0.5]] plims = [[np.log10(1.), 1.2], [-2.3, 0.7], [-0.4, 0.6]] fignums = [4, 7, 8] pairs = [[0,1], [0,2], [1,2]] plt.ioff() pp = PdfPages(os.path.join(working_dir, "mcmc_results_{0}.pdf".format(modelname))) plt.figure(1, figsize=(9,6.5)) plt.minorticks_on() table_summary, table_results = [], [] sndata = dict(np.loadtxt("ppxf_results.dat", usecols=(0,10), dtype=str)) for i, d in enumerate(dists): weights = np.ones_like(d.data)/len(d.data) ax = plt.subplot(3,3,(4*i)+1) plt.tick_params(labelsize=10) N, bins, patches = plt.hist(d.data, color="w", ec="w", bins=30, range=tuple(lims[i]), normed=True) fracs = N.astype(float)/N.max() norm = Normalize(-.2* fracs.max(), 1.5 * fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.gray_r(norm(thisfrac)) thispatch.set_facecolor(color) x = np.linspace(d.data.min(), d.data.max(), 100) tot = np.zeros_like(x) # for m,w,c in zip(d.gmm.best.means_, d.gmm.best.weights_, # d.gmm.best.covars_): # y = w * normpdf(x, m, np.sqrt(c))[0] # ax.plot(x, y, "--b") # tot += y # ax.plot(x,tot, "-b", lw=2) # pdf = np.exp(logprob) # pdf_individual = responsibilities * pdf[:, np.newaxis] # print pdf_individual ylim = ax.get_ylim() plt.plot(x, d.best.pdf(x), "-r", label="AD = {0:.1f}".format( d.best.ad), lw=2.5, alpha=0.7) ax.set_ylim(ylim) # plt.legend(loc=2, prop={'size':8}) plt.axvline(d.best.MAPP, c="r", ls="--") plt.tick_params(labelright=True, labelleft=False, labelsize=10) plt.xlim(d.lims) if i < 2: plt.setp(ax.get_xticklabels(), visible=False) else: plt.xlabel(r"[$\mathregular{\alpha}$ / Fe]") plt.minorticks_on() summary.append([d.best.MAPP, d.uerr, d.lerr]) for ss in [d.MAPP, d.MAPPmin, d.MAPPmax, d.best.ad]: log.append(r"{0:10s}".format(r"{0:.5f}".format(ss))) logfile = os.path.join(working_dir, folder, "summary.txt".format(modelname)) with open(logfile, "w") as f: f.write("{0:28s}{1:10s}{2:10s}{3:10s}{6:10s}{4:10s}{2:10s}{3:10s}{6:10s}{5:10s}" "{2:10s}{3:10s}{6:10s}\n".format("#Spectra", "Log AGE", "LOWER", "UPPER", "[Z/H]", "[E/Fe]", "AD test")) f.write("".join(log)) ax = plt.subplot(3,3,4) hist2D(ages, metal, ax) plt.setp(ax.get_xticklabels(), visible=False) plt.ylabel("[Z/H]") ax = plt.subplot(3,3,7) hist2D(ages, alpha, ax) plt.ylabel(r"[$\mathregular{\alpha}$ / Fe]") plt.xlabel("log Age (Gyr)") ax = plt.subplot(3,3,8) plt.xlabel("[Z/H]") hist2D(metal, alpha, ax) # Annotations plt.annotate(r"Spectrum: {0} S/N={1:.1f}".format(name.upper(), sn), xy=(.7,.91), xycoords="figure fraction", ha="center", size=20) xys = [(.7,.84), (.7,.77), (.7,.70)] line = r"{0:28s}".format(spec) for j, par in enumerate([r"Log Age", r"[Z/H]", r"[$\alpha$/Fe]"]): text = r"{0}={1[0]:.2f}$^{{+{1[1]:.2f}}}_"" \ ""{{-{1[2]:.2f}}}$ dex".format(par, summary[j]) plt.annotate(text, xy=xys[j], xycoords="figure fraction", ha="center", size=20) line += "{0[1]:.5f}" plt.tight_layout(pad=0.2) # plt.pause(0.001) # plt.show(block=True) pp.savefig() plt.savefig(os.path.join(working_dir, "logs/mcmc_{0}_{1}.png".format(name, modelname)), dpi=100) plt.clf() pp.close()
weights = np.ones_like(d.data) / len(d.data) ax = plt.subplot(3, 3, (4 * i) + 1) # plt.tick_params(labelsize=10) N, bins, patches = plt.hist(d.data, color="b", ec="k", bins=30, range=tuple(lims[i]), normed=True, edgecolor="k", histtype='bar', linewidth=1.) fracs = N.astype(float) / N.max() norm = Normalize(-.2 * fracs.max(), 1.5 * fracs.max()) for thisfrac, thispatch in zip(fracs, patches): color = cm.gray_r(norm(thisfrac)) thispatch.set_facecolor(color) thispatch.set_edgecolor("w") x = np.linspace(d.data.min(), d.data.max(), 100) tot = np.zeros_like(x) # for m,w,c in zip(d.gmm.best.means_, d.gmm.best.weights_, # d.gmm.best.covars_): # y = w * normpdf(x, m, np.sqrt(c))[0] # ax.plot(x, y, "--b") # tot += y # ax.plot(x,tot, "-b", lw=2) # pdf = np.exp(logprob) # pdf_individual = responsibilities * pdf[:, np.newaxis] # print pdf_individual ylim = ax.get_ylim() plt.plot(x,