def display(): gui = ti.GUI('2D Simple viewer', (nx, 3 * ny)) p_img = cm.terrain(p.to_numpy()) u_img = cm.terrain(u_post.to_numpy()) v_img = cm.terrain(v_post.to_numpy()) img = np.concatenate((p_img, v_img, u_img), axis=1) while True: gui.set_image(img) gui.show()
def create_topo_cmap(): colors_undersea = cm.terrain(np.linspace(0, 0.17, 56)) colors_land = cm.terrain(np.linspace(0.25, 1, 200)) # combine them and build a new colormap colors = np.vstack((colors_undersea, colors_land)) cut_terrain_map = matplotlib.colors.LinearSegmentedColormap.from_list( 'cut_terrain', colors) return cut_terrain_map
def bar_plots_round_count(metrics): labels = ("center", "left", "right", "up", "down") data = [ metrics.center_side, metrics.left_side, metrics.right_side, metrics.up_side, metrics.down_side ] n = len(data) k = 10**int(log10(max(data))) m = k * (1 + max(data) // k) r = 1.5 w = r / n colors = [cm.terrain(i / n) for i in range(n)] fig, ax = plt.subplots() ax.axis("equal") for i in range(n): innerring, _ = ax.pie([m - data[i], data[i]], radius=r - i * w, startangle=90, labels=["", labels[i]], labeldistance=1 - 1 / (1.5 * (n - i)), textprops={"alpha": 0}, colors=["white", colors[i]]) plt.setp(innerring, width=w, edgecolor="white") plt.legend() plt.show()
def __init__(self, parent, name=None, z=None, lines=None, color=pg.mkColor(45, 217, 207)): self.parent = parent self.read_regular() self.active = False color = cm.terrain(1, bytes=True)[:3] + (200, ) self.pen = pg.mkPen(color=color, width=0.5, style=Qt.SolidLine) self.name = name self.z = z if lines is None and self.name in self.doublet.keys(): self.regular = True self.l = self.doublet[self.name] else: self.regular = False if lines is None: lines = [] self.l = lines self.lines, self.labels = [], [] self.temp = None if self.name is not None and self.z is not None: self.draw(add=False)
def run_Model(self, reef, input_vector): reef.convert_vector(self.communities, input_vector, self.sedsim, self.flowsim) #model.py self.initial_sed, self.initial_flow = reef.load_xml( self.input, self.sedsim, self.flowsim) if self.vis[0] == True: reef.core.initialSetting(size=(8, 2.5), size2=(8, 3.5)) # View initial parameters reef.run_to_time(self.simtime, showtime=100.) if self.vis[1] == True: from matplotlib.cm import terrain, plasma nbcolors = len(reef.core.coralH) + 10 colors = terrain(np.linspace(0, 1.8, nbcolors)) nbcolors = len(reef.core.layTime) + 3 colors2 = plasma(np.linspace(0, 1, nbcolors)) reef.plot.drawCore(lwidth=3, colsed=colors, coltime=colors2, size=(9, 8), font=8, dpi=300) output_core = reef.plot.core_timetodepth( self.communities, self.core_depths) #modelPlot.py # predicted_core = reef.convert_core(self.communities, output_core, self.core_depths) #model.py # return predicted_core print('output_core_shape', output_core.shape) return output_core
def new_viewer(topo_file): import numpy as np import imageio, PIL.Image import stripy, lavavu print("Building spherical mesh ", flush=True) res_lon = 1800 res_lat = 900 mesh = stripy.hybrid_st_meshes.warped_xy_mesh_sphere(res_lon=res_lon, res_lat=res_lat) print("Reading topography data file ", flush=True) topography_data = np.array(imageio.imread(topo_file)) height = np.array( PIL.Image.fromarray(topography_data.view()).resize( (res_lon, res_lat))).astype(float) hrange = height.max() - height.min() height0 = (height - height.min()) / hrange XX = mesh.XX YY = mesh.YY ZZ = mesh.ZZ print("Building 3D viewer ") lv1 = lavavu.Viewer(border=False, resolution=[1066, 666], background="#FFFFFF") lv1["axis"] = False lv1['specular'] = 0.1 shrink_surface = 1.0 + 0.05 * height0.reshape(-1) tris1 = lv1.triangles("surfacemap", wireframe=False, colour="#000000:0.0") tris1.vertices( [XX * shrink_surface, YY * shrink_surface, ZZ * shrink_surface]) tris1.indices(mesh.simplices) tris1.texcoords([mesh.SS, mesh.TT]) from matplotlib import cm from matplotlib.colors import Normalize print("Laying down topography image") terrain_norm = Normalize(vmin=-5000.0, vmax=10000.0) texdata = cm.terrain(terrain_norm(topography_data)) tris1.texture(texdata, flip=False) print("Launching 3D viewer") lv1.window(menu=False) return lv1
def solve(self): gui = ti.GUI('2D Heat conduction', (self.nx, self.ny)) self.init() for i in range(self.iter): T_img = cm.terrain(self.T.to_numpy()) gui.set_image(T_img) filename = f'frame_{i:05d}.png' gui.show(filename) for e in gui.get_events(ti.GUI.PRESS): if e.key == ti.GUI.LMB: print("Clicked on: ", e.pos[0], e.pos[1]) self.on_click(e) self.temp_update()
def save_core(self, reef, naccept): path = '%s/%s' % (self.filename, naccept) if not os.path.exists(path): os.makedirs(path) # Initial settings # reef.core.initialSetting(size=(8, 2.5), size2=(8, 4.5), dpi=300, fname='%s/a_thres_%s_' % (path, naccept)) from matplotlib.cm import terrain, plasma nbcolors = len(reef.core.coralH) + 10 colors = terrain(np.linspace(0, 1.8, nbcolors)) nbcolors = len(reef.core.layTime) + 3 colors2 = plasma(np.linspace(0, 1, nbcolors)) # Community population evolution # reef.plot.speciesDepth(colors=colors, size=(8, 4), font=8, dpi=300, fname=('%s/b_popd_%s.png' % (path, naccept))) reef.plot.speciesTime(colors=colors, size=(8, 4), font=8, dpi=300, fname=('%s/c_popt_%s.png' % (path, naccept))) reef.plot.accomodationTime(size=(8, 4), font=8, dpi=300, fname=('%s/d_acct_%s.pdf' % (path, naccept))) # Draw core # reef.plot.drawCore(lwidth=3, colsed=colors, coltime=colors2, size=(9, 8), font=8, dpi=300, figname=('%s/e_core_%s' % (path, naccept)), filename=('%s/core_%s.csv' % (path, naccept)), sep='\t') return
def update_thumbnail(self, project, dedicated): if self.thumbnail(project) is not None and not dedicated: return db.delete_if(self.thumbnail(project)) if self.dedicated(project): tiffs = [self.dedicated(project)] else: tiffs = list(self.tiles(project)) # Crop image to actual region coords = [pt.z33n for pt in self.points] east = min(x for x, _ in coords) west = max(x for x, _ in coords) south = min(y for _, y in coords) north = max(y for _, y in coords) # Compute a suitable resolution res = max(north - south, east - west) / 640 nx = int((north - south) // res) ny = int((west - east) // res) x, y = np.meshgrid(np.linspace(north, south, nx), np.linspace(east, west, ny), indexing='ij') image = np.zeros((nx, ny)) for tiff in tiffs: tiff.interpolate(image, x, y) image /= np.max(image) image = colormap.terrain(image, bytes=True) filename = THUMBNAIL_ROOT / (hashlib.sha256(image.data).hexdigest() + '.png') image = Image.fromarray(image) image.save(filename) thumb = Thumbnail(filename=str(filename), project=project, polygon=self) with db.session() as s: s.add(thumb)
filepath = os.path.join(dir, listFiles[0]) fname = filepath.split("\\")[-1] #============================================================================== # define colourmap #============================================================================== cstart = 0.0 cstop = 0.30 nLinesInPlot = len(listFiles) cm_subsection = np.linspace(cstart, cstop, nLinesInPlot) del cstart, cstop, nLinesInPlot colors = [cmaps.terrain(x) for x in cm_subsection] ##============================================================================== ## Colourmap Example ##============================================================================== #import matplotlib.pyplot as plt # #from matplotlib import cm #from numpy import linspace # #start = 0.0 #stop = 1.0 #number_of_lines= 1000 #cm_subsection = linspace(start, stop, number_of_lines) # #colors = [ cmaps.jet(x) for x in cm_subsection ]
def initialSetting(self, font=8, size=(8, 2.5), size2=(8, 3.5), width=3, dpi=80, fname=None): """ Visualise the initial conditions of the model run. Parameters ---------- variable : font Environmental shape figures font size variable : size Environmental shape figures size variable : size2 Environmental function figures size variable : width Environmental shape figures line width variable : dpi Figure resolution variable : fname Save filename. """ from matplotlib.cm import terrain # nbcolors = len(self.names)+3 # JODIE EDIT: colour range from 0-1.8 from 0-1 # nbcolors = len(self.names)+3 nbcolors = len(self.names) + 8 colors = terrain(numpy.linspace(0, 1.25, nbcolors)) # print 'Community matrix aij representing the interactions between species:' # print '' cols = [] ids = [] for i in range(len(self.names)): cols.append('a' + str(i)) ids.append('a' + str(i) + 'j') df = pd.DataFrame(self.communityMatrix, index=ids) df.columns = cols # print df ############## <START JODIE ADDITION> ############## import os commstring = str(df) ############## <END JODIE ADDITION> ############## # print '' # print 'Species maximum production rates [m/y]:' # print '' index = [self.names] df = pd.DataFrame(self.prod, index=index) df.columns = ['Prod.'] # print df ############# <START JODIE ADDITION> ############## # prodstring = str(df) # edepthstring = str(self.edepth) # eflowstring = str(self.eflow) # esedstring = str(self.esed) # if self.inputFile == 'input_synth.xml': # # print "coreData.py -> input file:", self.inputFile # if not os.path.exists('data/synthetic_core'): # os.makedirs('data/synthetic_core') # filename = ('data/synthetic_core') # with file(('%s/initial_conditions.txt' % (filename)),'w') as outfile: # outfile.write('Community matrix:\n') # outfile.write(commstring) # outfile.write('\n\nCommunity maximum production rates [m/y]:\n') # outfile.write(prodstring) # outfile.write('\n\nCommunity depth functions [m]:\n') # outfile.write(edepthstring) # outfile.write('\n\nCommunity sediment tolerance functions [m/year]:\n') # outfile.write(esedstring) # outfile.write('\n\nCommunity flow tolerance functions [m/sec]:\n') # outfile.write(eflowstring) # elif self.inputFile == 'input_synth_windward_2.xml': # # print "coreData.py -> input file:", self.inputFile # if not os.path.exists('data/synthetic_core'): # os.makedirs('data/synthetic_core') # filename = ('data/synthetic_core') # with file(('%s/initial_conditions_windward.txt' % (filename)),'w') as outfile: # outfile.write('Community matrix:\n') # outfile.write(commstring) # outfile.write('\n\nCommunity maximum production rates [m/y]:\n') # outfile.write(prodstring) # outfile.write('\n\nCommunity depth functions [m]:\n') # outfile.write(edepthstring) # outfile.write('\n\nCommunity sediment tolerance functions [m/year]:\n') # outfile.write(esedstring) # outfile.write('\n\nCommunity flow tolerance functions [m/sec]:\n') # outfile.write(eflowstring) # elif self.inputFile == 'input_synth_leeward.xml': # # print "coreData.py -> input file:", self.inputFile # if not os.path.exists('data/synthetic_core'): # os.makedirs('data/synthetic_core') # filename = ('data/synthetic_core') # with file(('%s/initial_conditions_leeward.txt' % (filename)),'w') as outfile: # outfile.write('Community matrix:\n') # outfile.write(commstring) # outfile.write('\n\nCommunity maximum production rates [m/y]:\n') # outfile.write(prodstring) # outfile.write('\n\nCommunity depth functions [m]:\n') # outfile.write(edepthstring) # outfile.write('\n\nCommunity sediment tolerance functions [m/year]:\n') # outfile.write(esedstring) # outfile.write('\n\nCommunity flow tolerance functions [m/sec]:\n') # outfile.write(eflowstring) # else: # print "coreData.py -> input file:", self.inputFile ############# <END JODIE ADDITION> ############## # print '' # print 'Environmental trapezoidal shape functions:' # Visualise fuzzy production curve xs = numpy.linspace(0, self.esed.max(), num=201, endpoint=True) xf = numpy.linspace(0, self.eflow.max(), num=201, endpoint=True) xd = numpy.linspace(0, self.edepth.max(), num=201, endpoint=True) dtrap = [] strap = [] ftrap = [] for s in range(0, len(self.names)): dtrap.append(fuzz.trapmf(xd, self.edepth[s, :])) strap.append(fuzz.trapmf(xs, self.esed[s, :])) ftrap.append(fuzz.trapmf(xf, self.eflow[s, :])) self._plot_fuzzy_curve(xd, xs, xf, dtrap, strap, ftrap, size, dpi, font, colors, width, fname) if self.seaFunc is None and self.sedFunc is None and self.flowFunc is None: if self.sedfctx is None and self.flowfctx is None: return # print '' # print 'Environmental functions:' if self.seaFunc is not None and self.sedFunc is not None and self.flowFunc is not None: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax2 = fig.add_subplot(gs[4:8]) #, sharey=ax1) ax3 = fig.add_subplot(gs[8:12]) #, sharey=ax1) ax1.set_facecolor('#f2f2f3') ax2.set_facecolor('#f2f2f3') ax3.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax2.grid() ax3.grid() ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=5) ax3.locator_params(axis='x', nbins=5) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim( self.seaFunc(self.seatime).min() - 0.0001, self.seaFunc(self.seatime).max() + 0.0001) ax2.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax2.set_xlim( self.sedFunc(self.sedtime).min(), self.sedFunc(self.sedtime).max()) ax3.plot(self.flowFunc(self.flowtime), self.flowtime, linewidth=width, c='darkcyan') ax3.set_xlim( self.flowFunc(self.flowtime).min() - 0.0001, self.flowFunc(self.flowtime).max() + 0.0001) # Axis ax1.set_ylabel('Time [years]', size=font + 2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font + 3) tt2 = ax2.set_title('Water flow [m/sec]', size=font + 3) tt3 = ax3.set_title('Sediment input [m/year]', size=font + 3) tt1.set_position([.5, 1.03]) tt2.set_position([.5, 1.03]) tt3.set_position([.5, 1.03]) fig.tight_layout() # plt.show() plt.close() return if self.seaFunc is not None and self.sedFunc is not None: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax2 = fig.add_subplot(gs[4:8], sharey=ax1) ax1.set_facecolor('#f2f2f3') ax2.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax2.grid() ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=5) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim( self.seaFunc(self.seatime).min() - 0.0001, self.seaFunc(self.seatime).max() + 0.0001) ax2.plot(self.sedFunc(self.sedtime), self.sedtime, linewidth=width, c='sandybrown') ax2.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax2.set_xlim( self.sedFunc(self.sedtime).min(), self.sedFunc(self.sedtime).max()) # Axis ax1.set_ylabel('Time [years]', size=font + 2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font + 2) tt2 = ax2.set_title('Sediment input [m/year]', size=font + 2) tt1.set_position([.5, 1.03]) tt2.set_position([.5, 1.03]) fig.tight_layout() # plt.show() plt.close() if self.flowfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.flowfctx, self.flowfcty, linewidth=width, c='darkcyan') ax1.set_xlim(self.flowfctx.min(), self.flowfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font + 2) # Title tt1 = ax1.set_title('Water flow [m/sec]', size=font + 3) tt1.set_position([.5, 1.03]) # plt.show() plt.close() return if self.seaFunc is not None and self.flowFunc is not None: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax2 = fig.add_subplot(gs[4:8], sharey=ax1) ax1.set_facecolor('#f2f2f3') ax2.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax2.grid() ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=5) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim( self.seaFunc(self.seatime).min() - 0.0001, self.seaFunc(self.seatime).max() + 0.0001) ax2.plot(self.flowFunc(self.sedtime), self.sedtime, linewidth=width, c='darkcyan') ax2.set_xlim( self.flowFunc(self.sedtime).min(), self.flowFunc(self.sedtime).max()) # Axis ax1.set_ylabel('Time [years]', size=font + 2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font + 2) tt2 = ax2.set_title('Water flow [m/sec]', size=font + 2) tt1.set_position([.5, 1.03]) tt2.set_position([.5, 1.03]) fig.tight_layout() # plt.show() plt.close() if self.sedfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.sedfctx, self.sedfcty, linewidth=width, c='sandybrown') ax1.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax1.set_xlim(self.sedfctx.min(), self.sedfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font + 2) # Title tt1 = ax1.set_title('Sediment input [m/year]', size=font + 2) tt1.set_position([.5, 1.03]) # plt.show() plt.close() return else: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) if self.seaFunc is not None: ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim( self.seaFunc(self.seatime).min() - 0.0001, self.seaFunc(self.seatime).max() + 0.0001) else: ax1.plot(numpy.zeros(len(self.layTime)), self.layTime, linewidth=width, c='slateblue') ax1.set_xlim(-0.1, 0.1) # Axis ax1.set_ylabel('Time [years]', size=font + 2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font + 2) tt1.set_position([.5, 1.03]) # fig.savefig('sealevel.png', bbox_inches='tight') # plt.show() plt.close() if self.sedfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.sedfctx, self.sedfcty, linewidth=width, c='sandybrown') ax1.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax1.set_xlim(self.sedfctx.min(), self.sedfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font + 2) # Title tt1 = ax1.set_title('Sediment input [m/year]', size=font + 2) tt1.set_position([.5, 1.03]) # fig.savefig('sediment_input.png', bbox_inches='tight') # plt.show() plt.close() if self.flowfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1, 12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.flowfctx, self.flowfcty, linewidth=width, c='darkcyan') ax1.set_xlim(self.flowfctx.min(), self.flowfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font + 2) # Title tt1 = ax1.set_title('Water flow [m/sec]', size=font + 2) tt1.set_position([.5, 1.03]) # fig.savefig('flow_velocity.png', bbox_inches='tight') # plt.show() plt.close() # plt.show() plt.close() return
#As R has negative values, we'll use an instance of Normalize #see http://stackoverflow.com/questions/25023075/normalizing-colormap-used-by-facecolors-in-matplotlib norm = colors.Normalize() fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(7, 5)) m = cm.ScalarMappable(cmap=cm.jet) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.jet(norm(R))) ax.set_title('real$(Y^2_ 4)$', fontsize=20) m.set_array(R) fig.colorbar(m, shrink=0.8) #%% =========================================================================== l = 4 # degree m = 2 # order PHI, THETA = np.mgrid[0:2 * np.pi:300j, 0:np.pi:150j] R = sp.sph_harm(m, l, PHI, THETA).real s = 1 X = (s * R + 1) * np.sin(THETA) * np.cos(PHI) Y = (s * R + 1) * np.sin(THETA) * np.sin(PHI) Z = (s * R + 1) * np.cos(THETA) norm = colors.Normalize() fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), figsize=(7, 5)) m = cm.ScalarMappable(cmap=cm.jet) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.terrain(norm(R))) ax.set_title('1 + real$(Y^2_ 4)$', fontsize=20) m.set_array(R) fig.colorbar(m, shrink=0.8) #%%
labels = list("ABCDEFG") data = [21, 57, 88, 14, 76, 91, 26] #number of data points n = len(data) #find max value for full ring k = 10**int(log10(max(data))) m = k * (1 + max(data) // k) #radius of donut chart r = 1.5 #calculate width of each ring w = r / n #create colors along a chosen colormap colors = [cm.terrain(i / n) for i in range(n)] #create figure, axis fig, ax = plt.subplots() ax.axis("equal") #create rings of donut chart for i in range(n): #hide labels in segments with textprops: alpha = 0 - transparent, alpha = 1 - visible innerring, _ = ax.pie([m - data[i], data[i]], radius=r - i * w, startangle=90, labels=["", labels[i]], labeldistance=1 - 1 / (1.5 * (n - i)), textprops={"alpha": 0}, colors=["white", colors[i]])
def plot_rpf_phase(phase_distr, outfile): #Initialize fig and axes fig = plt.figure(figsize=(20, 13)) ax = fig.gca(projection='3d') axis_rate = 3 / float(len(phase_distr.keys())) ax.pbaspect = [axis_rate, 1, 0.5] # Aspect ratio based on proportions of x and y axis ''' If you want no square axis: edit the get_proj function inside site-packages\mpl_toolkits\mplot3d\axes3d.py (and remove .pyc file!): try: self.localPbAspect=self.pbaspect zoom_out = (self.localPbAspect[0]+self.localPbAspect[1]+self.localPbAspect[2]) except AttributeError: self.localPbAspect=[1,1,1] zoom_out = 0 xmin, xmax = self.get_xlim3d() / self.localPbAspect[0] ymin, ymax = self.get_ylim3d() / self.localPbAspect[1] zmin, zmax = self.get_zlim3d() / self.localPbAspect[2] # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0 worldM = proj3d.world_transformation(xmin, xmax, ymin, ymax, zmin, zmax) # look into the middle of the new coordinates R = np.array([0.5*self.localPbAspect[0], 0.5*self.localPbAspect[1], 0.5*self.localPbAspect[2]]) xp = R[0] + np.cos(razim) * np.cos(relev) * (self.dist+zoom_out) yp = R[1] + np.sin(razim) * np.cos(relev) * (self.dist+zoom_out) zp = R[2] + np.sin(relev) * (self.dist+zoom_out) E = np.array((xp, yp, zp)) then add one line to this script to set pbaspect: ax = fig.gca(projection='3d') ax.pbaspect = [2.0, 0.6, 0.25] #e.g. ''' #Make arrays for x- and y-coordinates x = np.asarray([0, 1, 2]) y = np.asarray(sorted(phase_distr.keys())) xmin = min(x) xmax = max(x) ymin = min(y) ymax = max(y) #Make a grid so that x- and y-coordinate for each point are given xpos, ypos = np.meshgrid(x[:] - 0.125, y[:] - 0.375) #Flatten: transform 2 dimensional array to 1 dimensional xpos = xpos.flatten('F') ypos = ypos.flatten('F') zpos = np.zeros_like( xpos) # Make for z-coordinate an array of zeroes of the same length #Length of the bars dx = 0.5 * np.ones_like(xpos) dy = dx.copy() #Sort phase distr dict based on keys and save as z lengths keys_sorted_1 = sorted(phase_distr.keys()) keys_sorted_2 = sorted(phase_distr[keys_sorted_1[0]].keys()) dz = [] for key2 in keys_sorted_2: for key1 in keys_sorted_1: dz.append(phase_distr[key1][key2]) #Color map cs = [] for i in range(0, 300, int(300 / len(y)) + 1): clr = cm.terrain(i) cs.append(clr) #Plot bars = ax.bar3d(xpos, ypos, zpos, dx, dy, dz, zsort='max', alpha=0.99, color=cs * 3) bars.set_edgecolor('k') #Axis ticks ticksxpos = np.arange(xmin, xmax + 1, 1) ticksxlabs = range(xmin, xmax + 1, 1) plt.xticks(ticksxpos, ticksxlabs) ax.tick_params(axis='x', which='major', labelsize=20, pad=15) ticksypos = np.arange(ymin, ymax + 1, 1) ticksylabs = range(ymin, ymax + 1, 1) plt.yticks(ticksypos, ticksylabs) ax.tick_params(axis='y', which='major', labelsize=20, pad=15) ax.tick_params(axis='z', which='major', labelsize=20, pad=40) #Axis labels plt.xlabel('Phase', labelpad=60, fontsize=30) plt.ylabel('RPF length', labelpad=100, fontsize=30) ax.set_zlabel('counts', labelpad=90, fontsize=30) #Camera point angle ax.view_init(azim=-30) #Place axes in the middle of the fig environment ax.set_position([-0.35, -0.15, 1.5, 1.5]) #Save as output fig.savefig(outfile) plt.close() return
import matplotlib.pyplot as plt import numpy as np from urllib import request from matplotlib import cm url = "https://wp.faculty.wmi.amu.edu.pl/pie.txt" data = request.urlopen(url) values = [] for i in data: values = i.decode('utf-8').split(' ') values.pop(-1) values = list(map(float, values)) spaces = (0.1, 0.03, 0.03, 0.03, 0.03) plt.pie(values, colors=cm.terrain(np.arange(0.0, 1.0, 0.2)), explode=spaces) plt.show()
def plot_aa_dependence(cath): """ cath is a Catecholamine_PMF object (see Preprocessing.py) Groups data according to cath.aa1 (the innermost amino acid) and makes boxplot for each possible amino acid Does the same grouping by cath.aa2 (the second amino acid) The result is one figure with two plots, one grouping by cath.aa1 the other by cath.aa2 """ Z = 16 colors = cm.terrain(np.linspace(0, 0.85, len(AA_ordered))) faded_colors = [(*c[:3], 0.8) for c in colors] faded_colors = [(*c[:3], 0.4) for c in colors] bp = dict(linestyle='-', lw=1.5, color='k', facecolor='r') fp = dict(marker='o', ms=8, ls='none', mec='k', mew=2) mp = dict(ls='-', lw=1., color='k') cp = dict(ls='-', lw=1.5, color='k') wp = dict(ls='-', lw=1.5, color='k') fig, axs = plt.subplots(figsize=(7, 5), ncols=1, nrows=2, gridspec_kw={'hspace': 0.4}) plt.ylabel("Free energy (kcal" + r"$mol^{-1}$)", fontsize=Z) grouping_col = ['aa1', 'aa2'] xlabels = ['AA1', 'AA2'] xx = np.linspace(1, len(AA_ordered), len(AA_ordered)) for ax, g_col, xlab in zip(axs, grouping_col, xlabels): ax.tick_params(labelsize=Z, size=6, width=1.6) tmp_df = cath.data.copy() tmp_df.dgs = tmp_df.dgs.apply(list) g_pts = tmp_df.groupby(g_col).agg({ 'dgs': 'sum' }).dgs.loc[[aa.upper() for aa in AA_ordered]] for g_aa, i, c, fc in zip(g_pts, xx, colors, faded_colors): bpl = ax.boxplot(g_aa, positions=[i], widths=0.6, patch_artist=True, boxprops=bp, flierprops=fp, medianprops=mp, capprops=cp, whiskerprops=wp) bpl['boxes'][0].set_facecolor(c) bpl['fliers'][0].set_markerfacecolor(fc) ax.set_ylim(-30, 0) ax.set_xlim(0.5, len(AA_ordered) + 0.5) ax.set_xticks(xx) ax.set_xticklabels(AA_ordered, fontsize=Z) ax.set_yticks([-30, -20, -10, 0]) ax.set_xlabel(xlab, fontsize=Z) # ax.set_ylabel("Free energy\n(kcal"+r"$mol^{-1}$)", fontsize=Z) ax.grid() plt.savefig("Plots/{}/aa_dependence.svg".format(cath.rname), format='svg', bbox_inches='tight') plt.savefig("Plots/{}/aa_dependence.png".format(cath.rname), format='png', dpi=300, bbox_inches='tight') plt.show() plt.close()
def initialSetting(self, font=8, size=(8,2.5), size2=(8,3.5), width=3, dpi=80, fname=None): """ Visualise the initial conditions of the model run. Parameters ---------- variable : font Environmental shape figures font size variable : size Environmental shape figures size variable : size2 Environmental function figures size variable : width Environmental shape figures line width variable : dpi Figure resolution variable : fname Save filename. """ from matplotlib.cm import terrain nbcolors = len(self.names)+3 colors = terrain(numpy.linspace(0, 1, nbcolors)) print 'Community matrix aij representing the interactions between communities:' print '' cols = [] ids = [] for i in range(len(self.names)): cols.append('a'+str(i)) ids.append('a'+str(i)+'j') df = pd.DataFrame(self.communityMatrix, index=ids) df.columns = cols print df print '' print 'Communities maximum production rates [m/y]:' print '' index = [self.names] df = pd.DataFrame(self.prod,index=index) df.columns = ['Prod.'] print df print '' print 'Environmental trapezoidal shape functions:' # Visualise fuzzy production curve xs = numpy.linspace(0, self.esed.max(), num=201, endpoint=True) xf = numpy.linspace(0, self.eflow.max(), num=201, endpoint=True) xd = numpy.linspace(0, self.edepth.max(), num=201, endpoint=True) dtrap = [] strap = [] ftrap = [] for s in range(0,len(self.names)): dtrap.append(fuzz.trapmf(xd, self.edepth[s,:])) strap.append(fuzz.trapmf(xs, self.esed[s,:])) ftrap.append(fuzz.trapmf(xf, self.eflow[s,:])) self._plot_fuzzy_curve(xd, xs, xf, dtrap, strap, ftrap, size, dpi, font, colors, width, fname) if self.seaFunc is None and self.sedFunc is None and self.flowFunc is None: if self.sedfctx is None and self.flowfctx is None: return return print '' print 'Environmental functions:' if self.seaFunc is not None and self.sedFunc is not None and self.flowFunc is not None: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax2 = fig.add_subplot(gs[4:8]) #, sharey=ax1) ax3 = fig.add_subplot(gs[8:12]) #, sharey=ax1) ax1.set_facecolor('#f2f2f3') ax2.set_facecolor('#f2f2f3') ax3.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax2.grid() ax3.grid() ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=5) ax3.locator_params(axis='x', nbins=5) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim(self.seaFunc(self.seatime).min()-0.0001, self.seaFunc(self.seatime).max()+0.0001) ax2.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax2.set_xlim(self.sedFunc(self.sedtime).min(), self.sedFunc(self.sedtime).max()) ax3.plot(self.flowFunc(self.flowtime), self.flowtime, linewidth=width, c='darkcyan') ax3.set_xlim(self.flowFunc(self.flowtime).min()-0.0001, self.flowFunc(self.flowtime).max()+0.0001) # Axis ax1.set_ylabel('Time [years]', size=font+2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font+3) tt2 = ax2.set_title('Water flow [m/s]', size=font+3) tt3 = ax3.set_title('Sediment input [m/d]', size=font+3) tt1.set_position([.5, 1.03]) tt2.set_position([.5, 1.03]) tt3.set_position([.5, 1.03]) fig.tight_layout() plt.show() if fname is not None: names = self.folder+'/'+'input-seasedflow.png' fig.savefig(names, bbox_inches='tight') return if self.seaFunc is not None and self.sedFunc is not None: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax2 = fig.add_subplot(gs[4:8], sharey=ax1) ax1.set_facecolor('#f2f2f3') ax2.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax2.grid() ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=5) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim(self.seaFunc(self.seatime).min()-0.0001, self.seaFunc(self.seatime).max()+0.0001) ax2.plot(self.sedFunc(self.sedtime), self.sedtime, linewidth=width, c='sandybrown') ax2.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax2.set_xlim(self.sedFunc(self.sedtime).min(), self.sedFunc(self.sedtime).max()) # Axis ax1.set_ylabel('Time [years]', size=font+2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font+2) tt2 = ax2.set_title('Sediment input [m/d]', size=font+2) tt1.set_position([.5, 1.03]) tt2.set_position([.5, 1.03]) fig.tight_layout() plt.show() if fname is not None: names = self.folder+'/'+'input-seased.png' fig.savefig(names) if self.flowfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.flowfctx, self.flowfcty, linewidth=width, c='darkcyan') ax1.set_xlim(self.flowfctx.min(), self.flowfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font+2) # Title tt1 = ax1.set_title('Water flow [m/s]', size=font+3) tt1.set_position([.5, 1.03]) plt.show() if fname is not None: names = self.folder+'/'+'input-flow.png' fig.savefig(names, bbox_inches='tight') return if self.seaFunc is not None and self.flowFunc is not None: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax2 = fig.add_subplot(gs[4:8], sharey=ax1) ax1.set_facecolor('#f2f2f3') ax2.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax2.grid() ax1.locator_params(axis='x', nbins=4) ax2.locator_params(axis='x', nbins=5) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim(self.seaFunc(self.seatime).min()-0.0001, self.seaFunc(self.seatime).max()+0.0001) ax2.plot(self.flowFunc(self.sedtime), self.sedtime, linewidth=width, c='darkcyan') ax2.set_xlim(self.flowFunc(self.sedtime).min(), self.flowFunc(self.sedtime).max()) # Axis ax1.set_ylabel('Time [years]', size=font+2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font+2) tt2 = ax2.set_title('Water flow [m/s]', size=font+2) tt1.set_position([.5, 1.03]) tt2.set_position([.5, 1.03]) fig.tight_layout() plt.show() if fname is not None: names = self.folder+'/'+'input-seaflow.png' fig.savefig(names, bbox_inches='tight') if self.sedfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.sedfctx, self.sedfcty, linewidth=width, c='sandybrown') ax1.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax1.set_xlim(self.sedfctx.min(), self.sedfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font+2) # Title tt1 = ax1.set_title('Sediment input [m/d]', size=font+2) tt1.set_position([.5, 1.03]) plt.show() if fname is not None: names = self.folder+'/'+'input-sed.png' fig.savefig(names, bbox_inches='tight') return else: matplotlib.rcParams.update({'font.size': font}) fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) if self.seaFunc is not None: ax1.plot(self.seaFunc(self.seatime), self.seatime, linewidth=width, c='slateblue') ax1.set_xlim(self.seaFunc(self.seatime).min()-0.0001, self.seaFunc(self.seatime).max()+0.0001) else: ax1.plot(numpy.zeros(len(self.layTime)), self.layTime, linewidth=width, c='slateblue') ax1.set_xlim(-0.1, 0.1) # Axis ax1.set_ylabel('Time [years]', size=font+2) # Title tt1 = ax1.set_title('Sea-level [m]', size=font+2) tt1.set_position([.5, 1.03]) plt.show() if fname is not None: names = self.folder+'/'+'input-sea.png' fig.savefig(names) if self.sedfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.sedfctx, self.sedfcty, linewidth=width, c='sandybrown') ax1.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e')) ax1.set_xlim(self.sedfctx.min(), self.sedfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font+2) # Title tt1 = ax1.set_title('Sediment input [m/d]', size=font+2) tt1.set_position([.5, 1.03]) plt.show() if fname is not None: names = self.folder+'/'+'input-sed.png' fig.savefig(names, bbox_inches='tight') if self.flowfcty is not None: fig = plt.figure(figsize=size2, dpi=dpi) gs = gridspec.GridSpec(1,12) ax1 = fig.add_subplot(gs[:4]) ax1.set_facecolor('#f2f2f3') # Legend, title and labels ax1.grid() ax1.locator_params(axis='x', nbins=4) ax1.locator_params(axis='y', nbins=10) ax1.plot(self.flowfctx, self.flowfcty, linewidth=width, c='darkcyan') ax1.set_xlim(self.flowfctx.min(), self.flowfctx.max()) # Axis ax1.set_ylabel('Depth [m]', size=font+2) # Title tt1 = ax1.set_title('Water flow [m/s]', size=font+2) tt1.set_position([.5, 1.03]) plt.show() if fname is not None: names = self.folder+'/'+'input-flow.png' fig.savefig(names, bbox_inches='tight') plt.show() return
def update(self): for i, doublet in enumerate(self): doublet.redraw(pen=pg.mkPen( cm.terrain(0.1 + 0.9 * i / len(self), bytes=True)[:3] + (200, )))
def compare_segments(self, beta, nM=3): # make sure strings are caste beta = float(beta) nM = int(nM) # check that it hasn't already been genereated plotname = os.path.join(self.filepath, 'tmp/segments_barplot-beta_{:.6f}-nM_{}.png'.format(beta, nM)) # for cherrypy retrival plotname_short = 'segments_barplot-beta_{:.6f}-nM_{}.png'.format(beta, nM) if os.path.exists(plotname): # format and return image_tmpl = lookup.get_template("singleimage.html.mako") tmpl = lookup.get_template("main.html.mako") return tmpl.render(title="cbayes inspector", header=self.string_directory, navigation=self.compare_segs_dict, footer="FOOTER", content = image_tmpl.render(filename=plotname_short, title="Model Probs for Each Data Segment") ) # for proper sorting of segments def segment_keys(args): seg1, seg2 = args return (seg1,-seg2) segment_labels = sorted(self.prob_dirs.keys(), key=segment_keys) number_dirs = len(segment_labels) # get top nM models for all inferEM directories topmodels = get_top_models(self.directory, self.prob_dirs, beta, nM) number_models = len(topmodels) # build data data = [] baseline = [] for n, em in enumerate(topmodels): data.append([0 for t in range(number_dirs)]) baseline.append( [0 for t in range(number_dirs)]) # populate fields for n, em in enumerate(topmodels): for s, seg in enumerate(segment_labels): focusdir = os.path.join(self.directory, self.prob_dirs[seg]) modelprobs = get_model_probs(focusdir, beta) data[n][s] = modelprobs[em] if n == 0: baseline[n][s] = 0. else: baseline[n][s] = baseline[n-1][s] + data[n-1][s] #import matplotlib.cm as cm from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('small') # define colormap colors = iter(cm.terrain(np.linspace(0, 1, number_models))) # make stacked bar plot ind = np.arange(1, number_dirs + 1) fig = plt.figure() ax = fig.add_subplot(111) plots = [] for n, em in enumerate(topmodels): plots.append(ax.bar(ind, data[n], bottom=baseline[n], align='center', alpha=0.75, color=next(colors))) plt.ylabel('Probabilities') plt.xticks(ind, segment_labels, rotation=25) plt.yticks([0., 0.25, 0.5, 0.75, 1.0]) colors = [p[0] for p in plots] # modify axis to fit legend box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 1.25, box.height]) # create legend ax.legend(tuple(colors), topmodels, loc='center left', bbox_to_anchor=(1, 0.5), prop=fontP) # make sure bounding box is good plt.tight_layout() plt.savefig(plotname) # clear plot plt.clf() # format and return image_tmpl = lookup.get_template("singleimage.html.mako") tmpl = lookup.get_template("main.html.mako") return tmpl.render(title="cbayes inspector", header=self.string_directory, navigation=self.compare_segs_dict, footer="FOOTER", content = image_tmpl.render(filename=plotname_short, title="Model Probs for Each Data Segment") )