def plot_mat(data): # Three subplots sharing both x/y axes f, axarray = plt.subplots(16, sharex=True, sharey=True) for i, row in enumerate(data): axarray[i].plot(range(len(row)), row, 'g') # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. f.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in f.axes], visible=False) plt.setp([a.get_yticklabels() for a in f.axes], visible=False) axarray[0].set_title('10 minute EEG Reading for Patient') axarray[int(len(axarray) / 2)].set_ylabel('Magnitude') axarray[-1].set_xlabel('Time') font = {'family': 'normal', 'weight': 'bold', 'size': 48} plt.rc('font', **font) plt.show()
def runAnalysis( saveDir, mdTrajectory , timePerFrame ): # Pure radius of gyration print "Calculating radius of gyration for trajectory" tmp = [] for ts in mdTrajectory.trajectory: time = ts.frame*timePerFrame / 1000 tmp.append([time,rgyr(mdTrajectory)]) rg = numpy.array(tmp) # Run the block analysis results = [] for nblocks in xrange(5,20): print "Running for "+str(nblocks)+" blocks" results.append(blocked(mdTrajectory, nblocks, rgyr)) r = numpy.array(results) # Print block analysis 'family' : 'Arial', font = { 'weight' : 'normal', 'size' : 10} plt.rc('font', **font) subplot(221) errorbar(r[:,0], r[:,2], yerr=r[:,3], rasterized=True) xlabel("number of blocks") ylabel(r"$\langle R_{\rm{gyr}} \rangle$ ($\AA$)") subplot(222) errorbar(r[:,1], r[:,2], yerr=r[:,3], rasterized=True) xlabel("block size") ylabel(r"$\langle R_{\rm{gyr}} \rangle$ ($\AA$)") subplot(223) plot(rg[:,0], rg[:,1], rasterized=True) xlabel("Time (ns)") ylabel(r"$R_{\rm{gyr}}$ ($\AA$)") subplot(224) plot(r[:,1]*timePerFrame/1000., numpy.divide(r[:,3] , numpy.sqrt(r[:,0]) ) , rasterized=True) xlabel("block length (ns)") ylabel("Blocked Standard Error") savefig(saveDir+"/analysis/plots/blocks.pdf") print "Wrote ./figures/blocks.{pdf,png}" % vars()
def plot_mat(data): # Three subplots sharing both x/y axes f, axarray = plt.subplots(16, sharex=True, sharey=True) for i, row in enumerate(data): axarray[i].plot(range(len(row)), row, 'g') # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. f.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in f.axes], visible=False) plt.setp([a.get_yticklabels() for a in f.axes], visible=False) axarray[0].set_title('10 minute EEG Reading for Patient') axarray[int(len(axarray) / 2)].set_ylabel('Magnitude') axarray[-1].set_xlabel('Time') font = {'family': 'normal', 'weight': 'bold', 'size': 48} plt.rc('font', **font) plt.show()
import sys import subprocess import numpy as np import fluidfoam from pylab import matplotlib, plt, show plt.rcParams.update({'font.size': 16}) plt.rc('font', family='serif') plt.rc('text', usetex=True) font = {'family': 'serif', 'size': 16, 'serif': ['computer modern roman']} plt.rc('font', **font) plt.rc('legend', **{'fontsize': 16}) matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] matplotlib.rcParams["legend.framealpha"] = None ################################################################## #Parameters to retreive dimensionless variables ################################################################## d = 160e-6 # particle diameter in m gravity = 9.81 # gravity in m/s2 rhoFluid = 1041 # fluid density in kg/m3 h = 0.0049 # initial granular height in m timeAdim = (d / gravity)**0.5 velAdim = 1000. * (gravity * d)**0.5 pressureAdim = rhoFluid * h * gravity ################################################################## # Experimental data extracted from Pailha et al. (2008) ##################################################################
import pygmo as pg from pylab import plt, np plt.rc('text', usetex=True) # https://github.com/matplotlib/matplotlib/issues/4495/ plt.rc('pgf', texsystem='pdflatex') def my_plot_non_dominated_fronts(points, marker='o', comp=[0, 1], up_to_rank_no=None): # We plot fronts, _, _, _ = pg.fast_non_dominated_sorting(points) # We define the colors of the fronts (grayscale from black to white) if up_to_rank_no is None: cl = list( zip(np.linspace(0.1, 0.9, len(fronts)), np.linspace(0.1, 0.9, len(fronts)), np.linspace(0.1, 0.9, len(fronts)))) else: cl = list( zip(np.linspace(0.1, 0.9, up_to_rank_no), np.linspace(0.1, 0.9, up_to_rank_no), np.linspace(0.1, 0.9, up_to_rank_no))) fig, ax = plt.subplots() count = 0 for ndr, front in enumerate(fronts): count += 1
all_data['185'] = numpy.loadtxt('dash185.dat',delimiter=',',skiprows=1) all_data['230'] = numpy.loadtxt('dash230.dat',delimiter=',',skiprows=1) with open('dash185.dat','r') as f: header = f.next().split(',') ncols = len(header)-1 xlbl = 'Time on station (hours)' #========================================================================= # create plots #========================================================================= plt.rc('text', usetex=True) font = {'family' : 'Times', 'weight' : 'bold', 'size' : 17} matplotlib.rc('font', **font) #========================================================================= # teeter angle #========================================================================= for i in xrange(1,len(header)-1): plt.figure(i) for k,v in all_data.iteritems(): plt.plot(v[:,0],v[:,i],linewidth=2.4,marker='o')
def bars(scheme, verbose=None, norm='load'): """ Figure to compare link proportional and usage proportional for a single scheme and put them in ./sensitivity/figures/scheme/ """ # Load data and results F = abs(np.load('./results/' + scheme + '-flows.npy')) quantiles = np.load('./results/quantiles_' + scheme + '_' + str(lapse) + '.npy') nNodes = 30 names = node_namer(N) # array of node labels links = range(len(F)) nodes = np.linspace(0.5, 2 * nNodes - 1.5, nNodes) nodes_shift = nodes + .5 for direction in directions: N_usages = np.load('./results/Node_contrib_' + scheme + '_' + direction + '_' + str(lapse) + '.npy') # Compare node transmission to mean load if verbose: print('Plotting node comparison - ' + scheme + ' - ' + direction) # sort node names for x-axis Total_usage = np.sum(N_usages, 1) node_ids = np.array(range(len(N))).reshape((len(N), 1)) node_mean_load = [n.mean for n in N] # Vector for normalisation if norm == 'cap': normVec = np.ones(nNodes) * sum(quantiles) else: normVec = node_mean_load # Calculate node proportional EU_load = np.sum(node_mean_load) Total_caps = sum(quantiles) Node_proportional = node_mean_load / EU_load * Total_caps / normVec Node_proportional = np.reshape(Node_proportional, (len(Node_proportional), 1)) # Calculate link proportional link_proportional = linkProportional(N, link_dic, quantiles) link_proportional = [link_proportional[i] / normVec[i] for i in range(nNodes)] # Calculate old usage proportional if direction == 'combined': old_usages = np.load('./linkcolouring/old_' + scheme + '_copper_link_mix_import_all_alpha=same.npy') old_usages += np.load('./linkcolouring/old_' + scheme + '_copper_link_mix_export_all_alpha=same.npy') else: old_usages = np.load('./linkcolouring/old_' + scheme + '_copper_link_mix_' + direction + '_all_alpha=same.npy') avg_node_usage = np.sum(np.sum(old_usages, axis=2), axis=0) / 70128. avg_EU_usage = np.sum(np.sum(np.sum(old_usages, axis=2), axis=0)) / 70128. avg_node_usage /= avg_EU_usage avg_node_usage /= normVec avg_node_usage *= 500000 # Calculate usage and sort countries by mean load normed_usage = Total_usage / normVec normed_usage = np.reshape(normed_usage, (len(normed_usage), 1)) node_mean_load = np.reshape(node_mean_load, (len(node_mean_load), 1)) data = np.hstack([normed_usage, node_ids, node_mean_load, link_proportional, Node_proportional]) data_sort = data[data[:, 2].argsort()] names_sort = [names[int(i)] for i in data_sort[:, 1]] # flip order so largest is first names_sort = names_sort[::-1] link_proportional = data_sort[:, 3][::-1] Node_proportional = data_sort[:, 4][::-1] data_sort = data_sort[:, 0][::-1] plt.figure(figsize=(10, 4), facecolor='w', edgecolor='k') ax = plt.subplot(111) green = '#009900' blue = '#000099' # Plot node proportional plt.rc('lines', lw=2) plt.rc('lines', dash_capstyle='round') plt.plot(np.linspace(0, len(N) * 2 + 2, len(N)), Node_proportional, '--k') # Plot link proportional #plt.bar(nodes, link_proportional, width=1, color=green, edgecolor='none') # Plot old usage proportional plt.bar(nodes, avg_node_usage[loadOrder], width=1, color=green, edgecolor='none') # Plot usage proportional plt.bar(nodes_shift, data_sort, width=1, color=blue, edgecolor='none') # Magic with ticks and labels ax.set_xticks(np.linspace(2, len(N) * 2 + 2, len(N) + 1)) ax.set_xticklabels(names_sort, rotation=60, ha="right", va="top", fontsize=10.5) ax.xaxis.grid(False) ax.xaxis.set_tick_params(width=0) if norm == 'cap': ax.set_ylabel(r'$M_n/ \mathcal{K}^T$') else: # ax.set_ylabel(r'Network usage [MW$_T$/MW$_L$]') ax.set_ylabel(r'$M_n/\left\langle L_n \right\rangle$') maxes = [max(avg_node_usage), max(data_sort)] plt.axis([0, nNodes * 2 + .5, 0, 1.15 * max(maxes)]) # Legend artists = [plt.Line2D([0, 0], [0, 0], ls='dashed', lw=2.0, c='k'), plt.Rectangle((0, 0), 0, 0, ec=green, fc=green), plt.Rectangle((0, 0), 0, 0, ec=blue, fc=blue)] LABS = ['$M^1$', '$M^{3}_{old}$', '$M^{3}_{new}$'] leg = plt.legend(artists, LABS, loc='upper left', ncol=len(artists), columnspacing=0.6, borderpad=0.4, borderaxespad=0.0, handletextpad=0.2, handleheight=1.2) leg.get_frame().set_alpha(0) leg.get_frame().set_edgecolor('white') ltext = leg.get_texts() plt.setp(ltext, fontsize=12) # the legend text fontsize plt.savefig(figPath + scheme + '/network-usage-' + direction + '-' + norm + '.png', bbox_inches='tight') if verbose: print('Saved figures to ./figures/compareUsage/' + scheme + '/network-usage-' + direction + '-' + norm + '.png')
def runAnalysis( caseDirs , resultsDir , noReweight = False): # Do a reference for each one for refDir in caseDirs: # ID of reference case refID = refDir.split("/")[-1] # User info print "Doing PCA analysis with "+refDir+" as reference" # Get the PCA limits of component 1-2 plot limit = 10 with open(refDir+"/analysis/data/pca_limits_1", "r") as fi: limit = int(float(fi.read())) limit += 0.01 # Go through the case dirs to plot for caseDir in caseDirs: print "Using "+caseDir+" as case" # ID of case caseID = caseDir.split("/")[-1] ## PCA PLOTTING ON REF DIR PCA COMPONENTS ######################################### # Create & run cpptraj for plotting all cases on the axes of the first eigenvector # Good URLs for PCA in CPPTRAJ: # http://archive.ambermd.org/201404/0243.html # PCA plotter pcaHandler = pcaFuncs.PCA( resultsDir+"/plots/pcaComparison/PCA_"+caseID+"_on_"+refID+".pdf" ) # Create new submission file TEMPLATE = open( caseDir+"/ccptraj_analysis_pca.ptraj", 'r') TEMP = TEMPLATE.read().replace("[PCAREFERENCE]", refDir ) TEMPLATE.close() # Write the submission file FILE = open(caseDir+"/ccptraj_analysis_pca.ptraj","w"); FILE.write( TEMP ); FILE.close(); # Run the cpptraj utility os.system( "$AMBERHOME/bin/cpptraj -p "+caseDir+"/md-files/peptide_nowat.prmtop -i "+caseDir+"/ccptraj_analysis_pca.ptraj" ) # Do the plots of energy landscapes & distributions pcaHandler.plotPCA( "Case: "+caseID+". Ref case: "+refID, # Plot Title caseDir+"/analysis/data/" , # Data Dir "global_pca", # Eigenvector file eigenVectorCount = 2, # Only plot two plotDistibution = False, # Do not plot the distribution limits = limit ) # Save the plot pcaHandler.savePlot() ## REWEIGHTING OF PCA PLOTS ON RED DIR PCA COMPONENTS ##################################################### # Check if we should do a reweighted version if noReweight == False: if os.path.isfile( caseDir+"/md-logs/weights.dat" ): # User info print "aMD weights found. Now attempting 2D reweighting" # Prepare input file numLines = 0 with open(caseDir+"/analysis/data/global_pca", "r") as fi: with open(caseDir+"/analysis/data/global_pca_singleColumn", "w") as fo: next(fi) for line in fi: numLines += 1 fo.write( line.split()[1]+"\t"+line.split()[2]+"\n" ) # Set the discretization reqBins = 100 discretization = (2*limit) / reqBins # Get the max value of normal plot maxValue = math.ceil(pcaHandler.getLatestMax()) # Run the reweighting procedure command = "python $PLMDHOME/src/PyReweighting/PyReweighting-2D.py \ -input "+caseDir+"/analysis/data/global_pca_singleColumn \ -name "+caseDir+"/analysis/data/global_pca_singleColumn_reweighted \ -Xdim -"+str(limit)+" "+str(limit)+" \ -Ydim -"+str(limit)+" "+str(limit)+" \ -discX "+str(discretization)+" \ -discY "+str(discretization)+" \ -cutoff 10 \ -Emax "+str(maxValue)+" \ -job amdweight_CE \ -weight "+refDir+"/md-logs/weights.dat | tee -a reweight_variable.log" print "Running command:", command os.system( command ) # Create long file for PCA module with open(caseDir+"/analysis/data/global_pca_reweightedDone", "w") as fo: with open(caseDir+"/analysis/data/global_pca_singleColumn_reweighted-pmf-c2.dat", "r") as fi: frame = 0 for line in fi: temp = line.split() entries = int(float(temp[2])*10) for i in range(0,entries): fo.write( str(frame) + "\t" + temp[0] + "\t" + temp[1] +"\n" ) frame += 1 # Print block analysis 'family' : 'Arial', fig, ax = plt.subplots(figsize=(8, 8), nrows=1, ncols=1 ) font = {'weight' : 'normal','size' : 10} plt.rc('font', **font) # Now plot the 2d histogram hist = np.load(caseDir+"/analysis/data/global_pca_singleColumn_reweighted_c2EnergyHist.npy") xedges = np.load(caseDir+"/analysis/data/global_pca_singleColumn_reweighted_c2edgesX.npy") yedges = np.load(caseDir+"/analysis/data/global_pca_singleColumn_reweighted_c2edgesY.npy") # Remove points above limit for jy in range(len(hist[0,:])): for jx in range(len(hist[:,0])): if hist[jx,jy] >= maxValue: hist[jx,jy] = float("inf") # Do plot img = plt.imshow(hist.transpose(), interpolation='nearest', origin='lower',extent=[yedges[0], yedges[-1],xedges[0], xedges[-1]] , rasterized=True ) # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) # Create colorbar colorbar = plt.colorbar(img, ax=ax, cax = cax) colorbar.set_label("Kcal / mol") # Set title, labels etc plt.legend() ax.set_xlabel("PC1", fontsize=12) ax.set_ylabel("PC2", fontsize=12) ax.set_title( "PCA. Case: "+caseID+" Reweighted. Ref case: "+refID ) plt.rc('font', **font) # Save figure fig.savefig(resultsDir+"/plots/pcaComparison/PCA_"+caseID+"_on_"+refID+"_reweighted.pdf") ## CLUSTER PLOTS ON PCA COMPONENTS ################################## # Do both hier and dbscan for clusterType in ["dbscan","hier"]: # Instantiate the class if os.path.isfile(caseDir+"/analysis/data/cluster_"+clusterType+"_out"): print "Doing the "+clusterType+" cluster equivalent of the PCA plot" # Start the cluster handler. Load the file declaring cluster for each frame clusterHandler = cluster.clusterBase( caseDir+"/analysis/data/cluster_"+clusterType+"_out" ) # Separate the dataset. # global_pca is the projection file for this case on the ref modes numPCAdataSets = clusterHandler.separateDataSet( caseDir+"/analysis/data/global_pca", # Input file caseDir+"/analysis/data/cluster_"+clusterType+"_pca_", # Output files xColumn = 1 ) # Create lists of labels and files for plotting clusterLabels = [] clusterFiles = [] offset = 1 if clusterType == "hier" else 0 for i in range( 0+offset, numPCAdataSets+offset): clusterLabels.append( "Cluster "+str(i) ) clusterFiles.append( caseDir+"/analysis/data/cluster_"+clusterType+"_pca_d2_c"+str(i) ) # First one is noise if offset == 0: clusterLabels[0] = "Noise" myPlot.plotData( resultsDir+"/plots/pcaComparison/" , clusterType+"_"+caseID+"_on_"+refID, clusterLabels, clusterFiles , "PC2", xUnit = "PC1", scatter = True, legendLoc = 4, figWidth = 8, figHeight = 8, tightXlimits = False, legendFrame = 1, legendAlpha = 1, xLimits = [-limit,limit], yLimits = [-limit,limit] )
def runAnalysis( caseDir, timeFactor ): # User information print "Now Doing hier Cluster" # Instantiate the class handler = cluster.clusterBase( caseDir+"/analysis/data/cluster_hier_out" ) # RMSd PLOT numRmsdDataSets = handler.separateDataSet( caseDir+"/analysis/data/backbone.rmsd", caseDir+"/analysis/data/cluster_hier_rmsd_" ) # User info print "Number of datasets for RMSd: "+str(numRmsdDataSets) # Create lists of labels and files for plotting clusterLabels = [] clusterFiles = [] for i in range( 1, numRmsdDataSets+1): clusterLabels.append( "Cluster "+str(i) ) clusterFiles.append( caseDir+"/analysis/data/cluster_hier_rmsd_d1_c"+str(i) ) # Do the plottin myPlot.plotData( caseDir+"/analysis/plots" , "RMSd Hier Cluster Plot", clusterLabels, clusterFiles , "RMSd ($\AA$)", xFactor = timeFactor, scatter = True, legendLoc = 4 ) ## OCCUPANCY PLOT ################# # Get the data to plot names, fractions = [],[] with open(caseDir+"/analysis/data/cluster_hier_summary.dat","r") as fi: next(fi) for aline in fi: if aline: values = aline.split() names.append( "Cluster "+values[0] ) fractions.append( float(values[2]) ) # Create an array for the interactions y_pos = np.arange(len(names)) # Do a bar plot of fractions #'family' : 'Arial', pp = PdfPages( caseDir+"/analysis/plots/ClusterHierOccupancy.pdf" ) font = { 'weight' : 'normal', 'size' : 10} fig = plt.figure(figsize=(16,5)) plt.barh( y_pos, fractions, align = 'center', color = plt.rcParams['axes.color_cycle'][0] ) plt.yticks(y_pos, names) ax = fig.gca() ax.set_xlabel("Occupied Fraction", fontsize=12) ax.set_ylabel("", fontsize=12) plt.title( "Cluster Hier Occupancy Fraction" ) plt.rc('font', **font) plt.savefig(pp, format="pdf",dpi=100) pp.close() ## PCA PLOT ########### # Separate the dataset numPCAdataSets = handler.separateDataSet( caseDir+"/analysis/data/pca12-ca", caseDir+"/analysis/data/cluster_hier_pca_", xColumn = 1 ) # User info print "Number of datasets for PCA: "+str(numPCAdataSets) # Go through each PCA component for n in range(2,4): # Create lists of labels and files for plotting clusterLabels = [] clusterFiles = [] for i in range( 1, numPCAdataSets+1): clusterLabels.append( "Cluster "+str(i) ) clusterFiles.append( caseDir+"/analysis/data/cluster_hier_pca_d"+str(n)+"_c"+str(i) ) print "Calling plot" print "labels", clusterLabels print "files", clusterFiles myPlot.plotData( caseDir+"/analysis/plots" , "PCA Hier Cluster, 1vs"+str(n), clusterLabels, clusterFiles , "PC"+str(n), xUnit = "PC1", scatter = True, legendLoc = 4, figWidth = 8, figHeight = 8, tightXlimits = False, legendFrame = 1, legendAlpha = 1 )
def runAnalysis( caseDir , eps, minPoints, timeFactor ): # User information print "Now Doing dbscan Cluster" titlePostpend = "eps: "+str(eps)+", minPoints: "+str(minPoints) ## KDIST PLOT ############# if os.path.isfile( caseDir+"/analysis/data/Kdist.1.dat" ): myPlot.plotData( caseDir+"/analysis/plots" , "Kdist Plots", ["1-dist","2-dist","3-dist","4-dist","5-dist","6-dist"], [caseDir+"/analysis/data/Kdist.1.dat", caseDir+"/analysis/data/Kdist.2.dat", caseDir+"/analysis/data/Kdist.3.dat", caseDir+"/analysis/data/Kdist.4.dat", caseDir+"/analysis/data/Kdist.5.dat", caseDir+"/analysis/data/Kdist.6.dat"] , "k-dist", xUnit = "points", skipLines = 1, xLimits=[0,100]) # Instantiate the class if os.path.isfile(caseDir+"/analysis/data/cluster_dbscan_out"): # Start the handler handler = cluster.clusterBase( caseDir+"/analysis/data/cluster_dbscan_out" ) ## RMSd PLOT ############ numRmsdDataSets = handler.separateDataSet( caseDir+"/analysis/data/backbone.rmsd", caseDir+"/analysis/data/cluster_dbscan_rmsd_" ) # User info print "Number of datasets for RMSd: "+str(numRmsdDataSets) # Create lists of labels and files for plotting clusterLabels = [] clusterFiles = [] for i in range( 0, numRmsdDataSets): clusterLabels.append( "Cluster "+str(i) ) clusterFiles.append( caseDir+"/analysis/data/cluster_dbscan_rmsd_d1_c"+str(i) ) # First one is noise clusterLabels[0] = "Noise" # Do the plottin myPlot.plotData( caseDir+"/analysis/plots" , "RMSd DBscan Cluster Plot", clusterLabels, clusterFiles , "RMSd ($\AA$)", xFactor = timeFactor, scatter = True, legendLoc = 4 ) ## OCCUPANCY PLOT ################# # Get the data to plot names, fractions = [],[] with open(caseDir+"/analysis/data/cluster_dbscan_summary.dat","r") as fi: next(fi) for aline in fi: if aline: values = aline.split() names.append( "Cluster "+values[0] ) fractions.append( float(values[2]) ) # Create an array for the interactions y_pos = np.arange(len(names)) # Do a bar plot of fractions 'family' : 'Arial', pp = PdfPages( caseDir+"/analysis/plots/ClusterDBscanOccupancy.pdf" ) font = { 'weight' : 'normal', 'size' : 10} fig = plt.figure(figsize=(16,5)) plt.barh( y_pos, fractions, align = 'center', color = plt.rcParams['axes.color_cycle'][0] ) plt.yticks(y_pos, names) ax = fig.gca() ax.set_xlabel("Occupied Fraction", fontsize=12) ax.set_ylabel("", fontsize=12) plt.title( "Cluster DBscan Occupancy Fraction, "+titlePostpend ) plt.rc('font', **font) plt.savefig(pp, format="pdf",dpi=100) pp.close() ## PCA PLOT ########### # Separate the dataset numPCAdataSets = handler.separateDataSet( caseDir+"/analysis/data/pca12-ca", caseDir+"/analysis/data/cluster_dbscan_pca_", xColumn = 1 ) # User info print "Number of datasets for PCA: "+str(numPCAdataSets) # Go through each PCA component for n in range(2,4): # Create lists of labels and files for plotting clusterLabels = [] clusterFiles = [] for i in range( 0, numPCAdataSets): clusterLabels.append( "Cluster "+str(i) ) clusterFiles.append( caseDir+"/analysis/data/cluster_dbscan_pca_d"+str(n)+"_c"+str(i) ) # First one is noise clusterLabels[0] = "Noise" myPlot.plotData( caseDir+"/analysis/plots" , "PCA DBscan Cluster, 1vs"+str(n), clusterLabels, clusterFiles , "PC"+str(n), xUnit = "PC1", scatter = True, legendLoc = 4, figWidth = 8, figHeight = 8, tightXlimits = False, legendFrame = 1, legendAlpha = 1 )
def runAnalysis( caseDir ): # User info print "Plotting hydrogren bonds" # Output file name and location dataDir = caseDir+"/analysis/data/" plotDir = caseDir+"/analysis/plots/" # Do a histogram plot of Hbond information pp = PdfPages( plotDir+"hbonds.pdf" ) # Get the data to plot names, fractions, avgDists, avgAngles = [],[],[],[] qbfile = open(dataDir+"hbond.avg","r") n = 0 for aline in qbfile: if n > 1 and n < 17: if aline: values = aline.split() names.append( values[0]+" - "+values[1] ) fractions.append( float(values[4]) ) avgDists.append( float(values[5]) ) avgAngles.append( float(values[6]) ) n = n + 1 # Create an array for the interactions y_pos = np.arange(len(names)) # Set the plotting font and default size 'family' : 'Arial', font = { 'weight' : 'normal', 'size' : 10} # Color of the bars color = plt.rcParams['axes.color_cycle'][0] # Do a bar plot of fractions fig = plt.figure(figsize=(16,5)) plt.barh(y_pos, fractions, align='center', color=color) plt.yticks(y_pos, names) ax = fig.gca() ax.set_xlabel("Occupied Fraction", fontsize=12) ax.set_ylabel("H-bond Interaction", fontsize=12) plt.title( "Hydrogen Bonds: Occupancy" ) plt.rc('font', **font) plt.savefig(pp, format="pdf",dpi=300) # Do a bar plot of avg dists fig = plt.figure(figsize=(16,5)) plt.barh(y_pos, avgDists, align='center', color=color) plt.yticks(y_pos, names) ax = fig.gca() ax.set_xlabel("Average Distance", fontsize=12) ax.set_ylabel("H-bond Interaction", fontsize=12) plt.title( "Hydrogen Bonds: Average Distance" ) plt.rc('font', **font) plt.savefig(pp, format="pdf",dpi=300) # Do a bar plot of avg angles fig = plt.figure(figsize=(16,5)) plt.barh(y_pos, avgAngles, align='center', color=color) plt.yticks(y_pos, names) ax = fig.gca() ax.set_xlabel("Average Angle", fontsize=12) ax.set_ylabel("H-bond Interaction", fontsize=12) plt.title( "Hydrogen Bonds: Average Angle" ) plt.rc('font', **font) plt.savefig(pp, format="pdf",dpi=300) # Close the figure pp.close()
def plotPCA( self, plotTitleIdentifier, dataDir, eigenVectorFile , eigenValueFile = False , eigenVectorCount = 4, plotDistibution = True, limits = False ): # If this is the first plot, create grid if self.subPlots == 0: self.createPdfPage() # User info print "Doing principal component analysis" # Do the four principal vectors frames = [] # Principal components pcs = [] for i in range( 0, eigenVectorCount ): pcs.append([]) # Go through analysis file and get eigenvalues if eigenValueFile != False: eigenValues = [] eigenValueTotal = 0 with open(dataDir+eigenValueFile,"r") as f: for line in f: temp = line.split() eigenValueTotal += float(temp[1]) eigenValues.append(float(temp[1])) eigenValues = (np.array(eigenValues) / eigenValueTotal) * 100 # Get the file with all the projection data pcaFile = open(dataDir+eigenVectorFile,"r") n = 0 for aline in pcaFile: if n > 1 and aline: values = aline.split() # Add frames frames.append( int(values[0]) ) # If requesting more vectors than present if eigenVectorCount > len(values): raise Exception("CPPTRAJ has not projected "+str(eigenVectorCount)+" vectors") # Add to vectors for i in range( 0, eigenVectorCount ): pcs[i].append( float(values[i+1]) ) n = n + 1 # Create numpy arrays frames = np.array( frames ) self.np_arrays = [ np.array( pc ) for pc in pcs ] # Set the plotting font and default size 'family' : 'Arial', font = { 'weight' : 'normal', 'size' : 10} # Do a plot for each PCA for component in range( 1, len(self.np_arrays) ): # User Info print "Plotting component 1 vs. "+str(component) # Normalize the data DeltaG = -kb T * [ ln( P(v1,v2) ) - ln Pmax ] boltzman = 0.0019872041 temperature = 300 # Plot both distribution & Energy Landscape for plotType in [ "energy", "distribution" ] if plotDistibution else [ "energy" ]: # New subplot ax = self.getActiveAx() # Increase subplot counter self.subPlots += 1 # Do the plotting if plotType == "energy": # Create the histogram without plotting, so we can set the units properly H, xedges, yedges = np.histogram2d(self.np_arrays[component], self.np_arrays[0], bins=100 ) H_normalized = H/len(self.np_arrays[0]) H = -1 * boltzman * temperature * (np.log( H_normalized )-np.log(np.max(H_normalized))) # Set max energy for vec in H: for val in vec: if not np.isinf(val) and val > self.latestMax: self.latestMax = val # Now plot the 2d histogram img = ax.imshow(H, interpolation='nearest', origin='lower',extent=[yedges[0], yedges[-1],xedges[0], xedges[-1]] , rasterized=True ) # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) # Create colorbar colorbar = plt.colorbar(img, ax=ax, cax = cax) colorbar.set_label("Kcal / mol") self.colorBars.append(colorbar) elif plotType == "distribution": # Directly do the 2d histogram of matplotlib _, _, _, img = ax.hist2d(self.np_arrays[0], self.np_arrays[component], bins=100 , rasterized=True, norm=LogNorm() ) colorbar = plt.colorbar(img, ax=ax) colorbar.set_label("Occurances") self.colorBars.append(colorbar) # Set limits if they are not specified if limits == False: print "Calculating plot limits based on data" mini = np.abs(np.min( [np.min(self.np_arrays[0]), np.min(self.np_arrays[component])] )) maxi = np.abs(np.max( [np.max(self.np_arrays[0]), np.max(self.np_arrays[component])] )) limits = int(math.ceil(np.max( [mini,maxi] ))) print "Setting plot limits to: ",limits ax.set_ylim([-limits,limits]) ax.set_xlim([-limits,limits]) # Save the limits for the component with open(dataDir+"pca_limits_"+str(component), "w") as fo: fo.write( str(limits) ) # Set title, labels etc plt.legend() if eigenValueFile != False: ax.set_xlabel("PC1 ({0:.2f}%)".format(eigenValues[0]), fontsize=12) ax.set_ylabel("PC"+str(component+1)+" ({0:.2f}%)".format(eigenValues[component]), fontsize=12) else: ax.set_xlabel("PC1", fontsize=12) ax.set_ylabel("PC"+str(component+1), fontsize=12) ax.set_title( "PCA. "+plotTitleIdentifier ) plt.rc('font', **font) # Save pdf page if it's filled if self.subPlots >= (self.rows*self.columns): print "Now saving to PDF. Number of plots: ",self.subPlots self.savePdfPage() self.subPlots = 0
import subprocess import sys import numpy as np import fluidfoam from pylab import plt, matplotlib, show plt.rc('text', usetex=True) font = {'family': 'serif', 'size': 16, 'serif': ['computer modern roman']} plt.rc('font', **font) plt.rc('legend', **{'fontsize': 16}) matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] ################################################################## #Parameters to retreive dimensionless variables ################################################################## d = 160e-6 # particle diameter in m gravity = 9.81 # gravity in m/s2 rhoFluid = 1041 # fluid density in kg/m3 h = 0.0049 # initial granular height in m timeAdim = (d / gravity)**0.5 velAdim = 1000. * (gravity * d)**0.5 pressureAdim = rhoFluid * h * gravity ################################################################## # Experimental data extracted from Pailha et al. (2008) ################################################################## data1 = np.genfromtxt('DATA/ExperimentalDataPailha2008/v_t_exp_562.txt', delimiter='\t',