def PLOT_MATRIX_SAMPLING(matrix,idx=None,sampling_size=None,colorm='jet'): from prettyplotlib import brewer2mpl import pylab red_purple = brewer2mpl.get_map('Blues', 'Sequential', 9).mpl_colormap green_purple = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap if sampling_size == None: sampling_size = [1e0,1e1,1e2,1e3,1e4,1e300] fig,ax = ppl.subplots(nrows=2,ncols=3) for ss in range(len(sampling_size)): nn = sampling_size[ss] pmatrix = 1 - np.exp(-nn*matrix) aa = ax[ss/3,ss%3] #plt.subplot(2,3,ss+1) #GeneralPlotter.PLOT_MATRIX(pmatrix,axis=1) #print ss/3,ss%3 pmatrix = GeneralPlotter.SORT_MATRIX(pmatrix,idx=idx,axis=1) pmatrix = np.flipud(pmatrix) #im = aa.matshow(pmatrix, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu) #pp=aa.imshow(pmatrix,interpolation='nearest',cmap=colorm) #fig.colorbar(pp,ax=aa) pcolormesh(fig,aa,pmatrix,center_value=0.5, ax_colorbar=aa,cmap=red_purple) aa.set_xticks([]) aa.set_yticks([]) aa.set_title(r'$n = %i$' % sampling_size[ss],fontsize=20) if ss==5: plt.title('$n = \infty$',fontsize=20)
def several_times(all_interval3, all_data3_3, names3, p_title3, time_real_1,time_real_2,time_real_3, delta_s,t_real, time_data, dycoms, fitting, s_point): fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors shape= np.shape(all_interval3) time_length=shape[1] print time_length k=2 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x='t='+str(time_buffer) ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label=name_x) k=6 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x='t='+str(time_buffer) ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[3],linewidth=l_w_1, label=name_x) k=12 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x='t='+str(time_buffer) ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[5],linewidth=l_w_1, label=name_x) k=15 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x='t='+str(time_buffer) ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[7],linewidth=l_w_1, label=name_x) k=32 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x='t='+str(time_buffer) ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1, label=name_x) ax.set_yscale('symlog') plt.xlabel('Liquid', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font) plt.xlim(0,3) plt.ylim([10,10**8]) plt.legend(loc=1, frameon=False) plt.show()
def plot_data_compare(interval1,data1_1, data1_2, data1_3, interval2, data2_1, data2_2, data2_3, interval3, data3_1, data3_2, data3_3, names1, names2, names3): #COLORS FOR PLOTTING fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors ######################################################################## #Scale data ######################################################################## data2_1=data2_1*30/18*1.3 data2_2=data2_2*30/18*1.3 data2_3=data2_3*30/18*1.3 data3_1=data3_1*50/18*1.4 data3_2=data3_2*50/18*1.4 data3_3=data3_3*50/18*1.4 ######################################################################## #Plot data ######################################################################## ax.plot(interval1,data1_3, color=color_set[1],linewidth=l_w_1, label=names1[3]) ax.plot(interval2,data2_3, color=color_set[3],linewidth=l_w_1, label=names2[3]) ax.plot(interval3,data3_3, color=color_set[5],linewidth=l_w_1, label=names3[3]) ######################################################################## #Plot properties ######################################################################## #GRID LINES #axes = plt.gca() #axes.grid(True) ax.set_yscale('symlog') #use 'symlog'= for symmetrical log or 'log' for only positive values plt.xlabel(r'$M/M_r$', fontsize=size_axes) #the argument r allows for latex code plt.ylabel('Relative amount of droplets', fontsize=size_axes) plt.xlim(0.1,2.2) plt.ylim([10,10**8]) plt.legend(loc=1, frameon=False) # set legend and the location #Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') plt.show()
def render_weights(file_name, queue, vmin, vmax, divergent, array_shape): from pylab import plt import matplotlib.animation as animation plotter = WeightsPlotter() fig = plt.figure(facecolor='gray', frameon=False) ax = fig.add_subplot(111) ax.set_aspect('equal') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.axis('off') if divergent: my_colormap = brewer2mpl.get_map('PiYG', 'diverging', 11).mpl_colormap else: my_colormap = brewer2mpl.get_map('OrRd', 'sequential', 9).mpl_colormap my_colormap.set_bad('#6ECFF6', 1.0) im = {} def update_img(array): array = plotter.plot_weights(array) if im.get('im', None) is None: im['im'] = ax.imshow(array, cmap=my_colormap, interpolation='nearest', vmin=vmin, vmax=vmax) aspect = array.shape[0] / float(array.shape[1]) fig.set_size_inches([7.2, 7.2 * aspect ]) # 720 pixels wide, variable height fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) im['im'].set_data(array) return im['im'] #legend(loc=0) ani = animation.FuncAnimation(fig, update_img, frames=IterableQueue(queue)) #writer = animation.writers['ffmpeg'](fps=30, bitrate=27*1024) ani.save(file_name, fps=30, extra_args=['-vcodec', 'libvpx', '-threads', '4', '-b:v', '1M'])
def draw_real_facebb_res(): from prettyplotlib import brewer2mpl from matplotlib.colors import LogNorm red_purple = brewer2mpl.get_map('RdPu', 'Sequential', 9).mpl_colormap names = [ 'TREES', 'CFAN', 'RCPR', 'IFA', 'CFSS', 'SDM', 'LBF', 'TCDCN', 'CCNF', 'GNDPM', 'DRMF', 'CFSS' ] bbsname = ['IBUG', 'V&J', 'HOG+SVM', 'HeadHunter'] mat = np.loadtxt('expdata/fig_confmatrix.txt') fig, ax = plt.subplots(1) ppl.pcolormesh(fig, ax, mat.T, xticklabels=names, yticklabels=bbsname) bestbbpairs = [2, 1, 1, 0, 0, 0, 2, 0, 0, 1, 0] for k in range(len(bbsname)): for k2 in range(11): if bestbbpairs[k2] == k: ax.annotate(('%1.5f' % mat[k2][k])[:6], xy=(k2 + 0.5, k + 0.5), bbox=dict(boxstyle="round", fc="cyan", alpha=0.8), horizontalalignment='center', verticalalignment='center') else: ax.annotate(('%1.5f' % mat[k2][k])[:6], xy=(k2 + 0.5, k + 0.5), horizontalalignment='center', verticalalignment='center') plt.xlim((0, 11))
def test_pcolormesh_positive_other_cmap(): red_purple = brewer2mpl.get_map('RdPu', 'sequential', 8).mpl_colormap np.random.seed(10) ppl.pcolormesh(np.random.uniform(size=(10, 10)), xticklabels=UPPERCASE_CHARS[:10], yticklabels=LOWERCASE_CHARS[-10:], cmap=red_purple)
def test_pcolormesh_other_cmap(): purple_green = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap fig, ax = plt.subplots(1) np.random.seed(10) ppl.pcolormesh(fig, ax, np.random.randn(10, 10), cmap=purple_green)
def P2b(): dataAll = mergeInOutPatientCKD(dataCKD_inpatient, dataCKD_outpatient) # get 2008 and 2009 data dataAll2008 = dataAll[dataAll['Year']==2008].drop_duplicates() dataAll2009 = dataAll[dataAll['Year']==2009].drop_duplicates() # initialize contingency table ContingencyTable = np.zeros((10,10)) for i in range(10): basePatient = dataAll2008[dataAll2008['CKD']== i] base_i = dataAll2009.loc[dataAll2009[idName].isin(basePatient[idName].as_matrix())] for j in range(10): ContingencyTable[i,j] = base_i[base_i['CKD']==j].shape[0] # for plotting contingency table plotArray = ((ContingencyTable)) print 'number of people in stage 5 is: %d' %(dataAll2008[dataAll2008['CKD']==5].shape[0]) print 'number of people in stage 6 (final stage) is: %d' %(dataAll2008[dataAll2008['CKD']==6].shape[0]) print 'number of people from stage 5 to 6 (final stage) is: %d' %(ContingencyTable[5,6]) # define a larger figure for plotting plt.figure(figsize=(15, 15)) ax = plt.subplot(111) # set tick location ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() from prettyplotlib import brewer2mpl red_purple = brewer2mpl.get_map('RdPu', 'Sequential', 9).mpl_colormap import seaborn as sns # give 0.0001 offset so that log scale can be applied sns.heatmap(ContingencyTable+0.0001, cmap=red_purple, annot=True, fmt='.0f', norm=LogNorm()) # define tick size plt.xticks(fontsize=14) plt.yticks(fontsize=14) # set label and title plt.xlabel('Year 2009 CKD Stage', fontsize = 16) plt.ylabel('Year 2008 CKD Stage', fontsize = 16) plt.title('Contingency Table', fontsize=20) # invert y axis for better visualization plt.gca().invert_yaxis() # save figure plt.savefig('ContingencyTable.png', bbox_inches='tight') plt.show()
def PLOT_MATRIX_SAMPLING(matrix, idx=None, sampling_size=None, colorm='jet'): from prettyplotlib import brewer2mpl import pylab red_purple = brewer2mpl.get_map('Blues', 'Sequential', 9).mpl_colormap green_purple = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap if sampling_size == None: sampling_size = [1e0, 1e1, 1e2, 1e3, 1e4, 1e300] fig, ax = ppl.subplots(nrows=2, ncols=3) for ss in range(len(sampling_size)): nn = sampling_size[ss] pmatrix = 1 - np.exp(-nn * matrix) aa = ax[ss / 3, ss % 3] #plt.subplot(2,3,ss+1) #GeneralPlotter.PLOT_MATRIX(pmatrix,axis=1) #print ss/3,ss%3 pmatrix = GeneralPlotter.SORT_MATRIX(pmatrix, idx=idx, axis=1) pmatrix = np.flipud(pmatrix) #im = aa.matshow(pmatrix, aspect='auto', origin='lower', cmap=pylab.cm.YlGnBu) #pp=aa.imshow(pmatrix,interpolation='nearest',cmap=colorm) #fig.colorbar(pp,ax=aa) pcolormesh(fig, aa, pmatrix, center_value=0.5, ax_colorbar=aa, cmap=red_purple) aa.set_xticks([]) aa.set_yticks([]) aa.set_title(r'$n = %i$' % sampling_size[ss], fontsize=20) if ss == 5: plt.title('$n = \infty$', fontsize=20)
def draw_color_mesh(self): ''' Draws a heatmap of pairs of heroes which co-occur in the winning and in the losing teams, useful to visualize the relationship between strong pairs of heroes which lead to victories vs. weak pairs of heroes which don't have much synergy ''' red_yellow = brewer2mpl.get_map('YlGnBu', 'Sequential', 9).mpl_colormap fig, ax = plt.subplots(1, figsize=(13, 10)) ax.set_xlim([0, self.c]) ax.set_ylim([0, self.c]) mesh = np.zeros((self.c, self.c), dtype=float) for i in range(0, self.c): for j in range(0, self.c): if i >= j: # Same hero cannot be picked twice continue if (i, j) in self.dwstat: if self.ddstat[(i, j)] != 0: k = round( self.dwstat[(i, j)] / float(self.ddstat[(i, j)] + self.dwstat[(i, j)]), 2) mesh[i][j] = k mesh[j][i] = k # *************************************************************** # # Code to calculate the max ratios in the heatmap # and obtain their hero indices too # Get the indices for the largest `num_largest` values. num_largest = 8 indices = mesh.argpartition(mesh.size - num_largest, axis=None)[-num_largest:] x, y = np.unravel_index(indices, mesh.shape) print "full:" print "x =", x print "y =", y print "Largest values:", mesh[x, y] # print "Compare to: ", np.sort(mesh, axis=None)[-num_largest:] # **************************************************************** # ppl.pcolormesh(fig, ax, mesh, cmap=red_yellow) fig.savefig('../Figures/HeatMap-heroPairs.png') plt.show() plt.clf()
def render_weights(file_name, queue, vmin, vmax, divergent, array_shape): from pylab import plt import matplotlib.animation as animation plotter = WeightsPlotter() fig = plt.figure(facecolor='gray', frameon=False) ax = fig.add_subplot(111) ax.set_aspect('equal') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.axis('off') if divergent: my_colormap = brewer2mpl.get_map('PiYG', 'diverging', 11).mpl_colormap else: my_colormap = brewer2mpl.get_map('OrRd', 'sequential', 9).mpl_colormap my_colormap.set_bad('#6ECFF6', 1.0) im = {} def update_img(array): array = plotter.plot_weights(array) if im.get('im', None) is None: im['im'] = ax.imshow(array, cmap=my_colormap, interpolation='nearest', vmin=vmin, vmax=vmax) aspect = array.shape[0] / float(array.shape[1]) fig.set_size_inches([7.2, 7.2*aspect]) # 720 pixels wide, variable height fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) im['im'].set_data(array) return im['im'] #legend(loc=0) ani = animation.FuncAnimation(fig,update_img, frames=IterableQueue(queue)) #writer = animation.writers['ffmpeg'](fps=30, bitrate=27*1024) ani.save(file_name, fps=30, extra_args=['-vcodec', 'libvpx', '-threads', '4', '-b:v', '1M'])
def test_pcolormesh_positive_other_cmap(): red_purple = brewer2mpl.get_map("RdPu", "sequential", 8).mpl_colormap fig, ax = plt.subplots(1) np.random.seed(10) ppl.pcolormesh( fig, ax, np.random.uniform(size=(10, 10)), xticklabels=string.uppercase[:10], yticklabels=string.lowercase[-10:], cmap=red_purple, )
def col_map (name, num_color): ''' 1) This function is designed to read a color set from ColorBrewer website http://bl.ocks.org/mbostock/5577023 2) Returns the color map Note: This function requires "brewer2mpl" library. ''' # Get color data from color_set = brewer2mpl.get_map(name, 'diverging', num_color, reverse=True).mpl_colormap ax = fig.add_subplot(1,3,2) np.random.seed(10) ppl.pcolormesh (fig, ax, np.random.randn(10,10),cmap=color_set) ax.set_title('Improved color map\nwith ColorBrewer color set',fontsize=11.5)
def draw_real_facebb_res(): from prettyplotlib import brewer2mpl from matplotlib.colors import LogNorm red_purple = brewer2mpl.get_map('RdPu', 'Sequential', 9).mpl_colormap names = ['TREES', 'CFAN', 'RCPR', 'IFA', 'CFSS', 'SDM', 'LBF', 'TCDCN', 'CCNF', 'GNDPM', 'DRMF','CFSS'] bbsname = ['IBUG','V&J','HOG+SVM','HeadHunter'] mat = np.loadtxt('expdata/fig_confmatrix.txt') fig, ax = plt.subplots(1) ppl.pcolormesh(fig, ax, mat.T,xticklabels=names,yticklabels=bbsname) bestbbpairs = [2,1,1,0,0,0,2,0,0,1,0] for k in range(len(bbsname)): for k2 in range(11): if bestbbpairs[k2] == k: ax.annotate(('%1.5f'%mat[k2][k])[:6],xy=(k2+0.5,k+0.5),bbox=dict(boxstyle="round", fc="cyan",alpha=0.8), horizontalalignment='center', verticalalignment='center') else: ax.annotate(('%1.5f'%mat[k2][k])[:6],xy=(k2+0.5,k+0.5), horizontalalignment='center', verticalalignment='center') plt.xlim((0,11))
def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ import prettyplotlib as ppl from prettyplotlib import brewer2mpl ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allfrequencies = [] plt = pretty_plot(12, 8) # Note that this complicated processing of frequencies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): frequencies = dos['frequencies'] densities = dos['densities'] if y is None: y = np.zeros(frequencies.shape) if self.stack: y += densities newdens = y.copy() else: newdens = densities allfrequencies.append(frequencies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allfrequencies.reverse() allpts = [] for i, (key, frequencies, densities) in enumerate(zip(keys, allfrequencies, alldensities)): allpts.extend(list(zip(frequencies, densities))) if self.stack: plt.fill(frequencies, densities, color=colors[i % ncolors], label=str(key)) else: ppl.plot(frequencies, densities, color=colors[i % ncolors], label=str(key), linewidth=3) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Frequencies (THz)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt
print(x_labels) fig, ax = plt.subplots(1) #rects1 = ax.bar(ind, y, width=0.5, color="#2ecc71", edgecolor="#3498db") ax.set_xticks(ind) ax.set_title('Reportes de incendio desde la cuenta @bomberos', size=22, fontproperties=prop, ) ax.tick_params(axis="x", color="gray", labelsize=8) ax.set_xticklabels(x_labels) plt.ylim([0, 60]) plt.xticks(rotation="90") # queremos color set2 = brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors color = set2[0] ax.set_xlabel('Fecha', size=14, fontproperties=prop, ) ax.set_ylabel('Número de tuits por día con palabra "INCENDIO"', size=14, fontproperties=prop, ) plt.plot(x_2014, y_2013, '#7f8c8d', x_2014, y_2014, '#27ae60', label='mi lengenda') ax.legend(['Año 2013', 'Año 2014']) plt.tight_layout()
def several_times_and_flight(all_interval3, all_data3_3, names3, p_title3, time_real_1,time_real_2,time_real_3, delta_s,t_real, time_data, dycoms, fitting, s_point, interval_flight, data_flight,interval_flight_2, data_flight_2, flight_err_2, data3_3, interval3): #setup colors fig, ax1 = plt.subplots() #fig, ax5 = plt.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('YlGnBu', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors color_set_4 = brewer2mpl.get_map('Purples', 'sequential', 9).mpl_colors shape= np.shape(all_interval3) time_length=shape[1] #sum of all particles sum_all_data3_3 = np.zeros(time_length) for i in np.arange(time_length): sum_all_data3_3[i]=np.sum(all_data3_3[:,i]) sum_all_data3_3[i]=sum_all_data3_3[i]-all_data3_3[0,i] ######################################################################## #Plot the flight data ######################################################################## data_flight=data_flight*0.9*10**7 #change amount of particles accoding to simulation data_flight_2=data_flight_2*0.9*10**7 flight_err_2 = data_flight_2[:] * flight_err_2[:] #error data seems wrong # actual flight thing now #ax1.plot(interval_flight,data_flight,zorder=10, color=color_set_4[4],marker='.',linestyle='None',markersize=m_s+9 , label='Flight data') ax1.plot(interval_flight_2,data_flight_2,zorder=10, color=color_set_4[7],marker='.',linestyle='None',markersize=m_s+9 , label='Flight data') #ax1.errorbar(interval_flight_2,data_flight_2,yerr=flight_err_2,zorder=10, color=color_set[8],marker='.',linestyle='None',markersize=m_s+9 , label='Flight data') ######################################################################## #Plot the data+fit ######################################################################## time_real_data=np.zeros(len(time_data)) for i in np.arange(len(time_data)): time_real_data[i]=round(time_data[i]*t_real/60,2) print 'real time',i,time_real_data[i] t_0 = 0 # timestep was before 55 G = 0.09/20 #cooling rate from tkstat plot_t = [59,82,107,133,159,186] #"timesteps" we want to plot t_sim=time_data[plot_t[:]] #simulation time-step from time_data l_c = [0,1,2,3,4,5] # for colors of brewer color scale j=0 #counter for colors for k in plot_t: time_real_data[k]=round(time_real_data[k],0) label_name='t=' + str(int(time_real_data[k])) + ' min' if (k < t_0 ): scale=1.0 else: scale = G*(t_sim[j]-t_0) ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[l_c[j]],linewidth=l_w_1, label=label_name) #ax5.plot(all_interval3[:,k]-scale,np.gradient(np.log(all_data3_3[:,k])),color=color_set[l_c[j]],linewidth=l_w_1, label=label_name) j=j+1 # if (k==fit_start): # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1) # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name) # print 'k' # #elif (k==24): # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1) # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name) # #elif (k==35): # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1) # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name) # elif (k==55): # j=3 # scale = G*(t_sim[j]-t_0) # print "AHAHAHAHAHAHA", scale # j=j+1 # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[3],linewidth=l_w_1) # ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[3],linewidth=l_w_1, label='Simulation ' + label_name) # #old value 1.065 # elif (k==79): # scale = .15 # scale = G*(t_sim[j]-t_0) # j=j+1 # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[5],linewidth=l_w_1) # ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[5],linewidth=l_w_1, label='Simulation ' + label_name) # #old value 1.08 # elif (k==99): # scale = .2 # scale = G*(t_sim[j]-t_0) # j=j+1 # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1) # ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[9],linewidth=l_w_1, label='Simulation ' + label_name) # #old value 1.104 # elif (k==144): # scale = .33 # scale = G*(t_sim[j]-t_0) # j=j+1 # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1) # ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[11],linewidth=l_w_1, label='Simulation ' + label_name) # #old value 1.138 # elif (k==166): # scale = .38 # scale = G*(t_sim[j]-t_0) # j=j+1 # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1) # ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[0],linewidth=l_w_1, label='Simulation ' + label_name) # #old value 1.153 # elif (k==188): # scale = .42 # scale = G*(t_sim[j]-t_0) # j=j+1 # #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1) # ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[2],linewidth=l_w_1, label='Simulation ' + label_name) #stuff for fits but not sure anymore fit_start=15 steps= np.arange(fit_start,189) c=1 l=0 b_new = np.zeros(len(steps)) a_new = np.zeros(len(steps)) N_integrate = np.zeros(len(steps)) sigma_square_new = np.zeros(len(steps)) for k in steps: log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(all_data3_3[:,k])): if (all_data3_3[i,k] != 0): log_data[i] = np.log(all_data3_3[i,k]) elif (all_data3_3[i,k] == 0): log_data[i]=all_data3_3[i,k] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break #POLYNOMIAL FIT z = np.polyfit(all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1], 2) p = np.poly1d(z) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) x = np.linspace(1.75,mean+6,1000) #alberto y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) #PLOT BLUE FITS AS BEFORE #if (k==fit_start): # ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[1], linestyle='--', linewidth=l_w_2) #elif (k==35): # ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[1], linestyle='--', linewidth=l_w_2) #c=c+2 #for the color code #CURVE FITTIN c_fixed=13.75 x_zero=1.6 def pol_func(x,a,b): return a*(x-x_zero)**2+b*(x-x_zero)+c_fixed #return a*(x-x_zero)**2+b*(x-x_zero)+c #return a*(x)**2+b*(x)+c fitpars, covmat = so.curve_fit(pol_func,all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1]) mean_new=fitpars[1]/(-2*fitpars[0]) sigma_square_calc=(1/(-2*fitpars[0])) #NEW Y WITH x=x-x_zero y_new=np.exp( (c_fixed+fitpars[1]**2/(4*-fitpars[0]))-((((x-x_zero)-mean_new)**2)/(2*sigma_square_calc)) ) #print 'CURVE FIT fitpars', fitpars #GET/CALCULATE FIT PARAMETERS a_new[l]=fitpars[0] b_new[l]=fitpars[1] sigma_square_new[l]=-1/(2*fitpars[0]) aa=a_new[l] bb=b_new[l] #CALCULATE THE AMOUNT OF DROPLETS IN THE TAIL def exp_pol_func(x): return np.exp(aa*(x-x_zero)**2+bb*(x-x_zero)+c_fixed) N_integrate2=scipy.integrate.quad(exp_pol_func, x_zero,10) N_integrate[l] = N_integrate2[0]/sum_all_data3_3[l+fit_start] #COUNT STEP +1 l=l+1 ############################################# #LINEAR FIT FOR a AND FOR b ############################################# def lin_func(x,a,b): #linear fit return a*(x)+b def pol2_func(x,a,b,c): #polynomial fit return a*(x)**2+b*x+c def tanh_func(x,a,b,c): #hyperbolicus tangential fit return c+a*np.tanh(x+b) def sqrt_func(x,a,b,c): #root fit return c+a*np.sqrt(x+b) def asympt_func(x,a,b,c): #asymptotic fit return c+b/x+a/(x**2) #fitpars_a_new, covmat_2 = so.curve_fit(lin_func,steps,a_new) fitpars_a_new, covmat_2 = so.curve_fit(asympt_func,steps,a_new) #fitpars_a_new, covmat_2 = so.curve_fit(tanh_func,steps,a_new) #fitpars_a_new, covmat_2 = so.curve_fit(sqrt_func,steps,a_new) #fitpars_a_new, covmat_2 = so.curve_fit(pol2_func,steps,a_new) fitpars_b_new, covmat_3 = so.curve_fit(lin_func,steps,b_new) fitpars_sigma_square_new, covmat_3 = so.curve_fit(lin_func,steps,sigma_square_new) time_part=np.arange(0,len(time_real_3)) fitpars_time, covmat_3 = so.curve_fit(lin_func,time_part,time_real_3) ###################################################################### #GENERAL EXTRAPOLATION ###################################################################### #USING ACTUAL FIT FOR time x = np.linspace(5,90,100) time_extrapol=fitpars_time[0]*x+fitpars_time[1] steps_time=fitpars_time[0]*steps+fitpars_time[1] #USING ACTUAL FIT FOR b test_b = fitpars_b_new[0]*x+fitpars_b_new[1] #USING ACTUAL FIT FOR a #a_fit = fitpars_a_new[0]*x+fitpars_a_new[1] a_fit = fitpars_a_new[0]*(1.0/x**2)+fitpars_a_new[1]*(1.0/x)+c_fixed #a_fit = fitpars_a_new[2]+fitpars_a_new[0]*np.tanh(x+fitpars_a_new[1]) #a_fit = fitpars_a_new[2]+fitpars_a_new[0]*np.sqrt(x+fitpars_a_new[1]) #a_fit = fitpars_a_new[0]*x**2+fitpars_a_new[1]*x + fitpars_a_new[2] #USING FIT FOR SIGMA_SQUARE sigma_square_new_fit = fitpars_sigma_square_new[0]*x+fitpars_sigma_square_new[1] ###################################################################### #SEVERAL STEPS FOR USING THE EXTRAPOLATION ###################################################################### #SEVERAL TIME STEPS several_x = np.arange(10,900,20) #from 10,20,30 ... 180,190 several_times=fitpars_time[0]*several_x+fitpars_time[1] several_test_b = fitpars_b_new[0]*several_x+fitpars_b_new[1] #several_a = fitpars_a_new[0]*several_x+fitpars_a_new[1] several_a = fitpars_a_new[0]*(1.0/several_x**2)+fitpars_a_new[1]*(1.0/several_x)+fitpars_a_new[2] #several_a = fitpars_a_new[2]+fitpars_a_new[0]*np.tanh(several_x+fitpars_a_new[1]) #several_a = fitpars_a_new[2]+fitpars_a_new[0]*np.sqrt(several_x+fitpars_a_new[1]) #several_a = fitpars_a_new[0]*several_x**2+fitpars_a_new[1]*several_x +fitpars_a_new[2] several_sigma_square_new = fitpars_sigma_square_new[0]*several_x+fitpars_sigma_square_new[1] ###################################################################### #SOLVE EQUATION FOR B NUMERICAL ###################################################################### b_solved = np.zeros(len(several_x)) a_sigma = np.zeros(len(several_x)) #a calculated from sigma for m in np.arange(len(several_x)): a_sigma[m]=-1/(2*several_sigma_square_new[m]) k_const=0.00075 k_const=0.002 def func_for_b(b_solve): return(np.exp(-b_solve**2/(4*a_sigma[m])+c_fixed)*np.sqrt(np.pi)*(1+scipy.special.erf(b_solve/(2*np.sqrt(-a_sigma[m])))))/(2*np.sqrt(-a_sigma[m]))-k_const*np.mean(sum_all_data3_3) b_initial_guess=-3 b_solved[m]= so.fsolve(func_for_b,b_initial_guess) print 'the mean of all droplets', np.mean(sum_all_data3_3) #FIRST NEW EXTRAPOLATION m=7 #decide which time step x_plot = np.linspace(1.5,6,100) #alberto print 'FIT IS AT TIMESTEP', several_times[m] #using new interpretation of b new_y_extrapolation_2=np.exp(c_fixed+(b_solved[m])*(x_plot-x_zero)-(1/(2*several_sigma_square_new[m])*(x_plot-x_zero)**2)) #ax1.plot(x_plot,new_y_extrapolation_2 , color=color_set[6], label=r'Extrapol t$\,\approx\,$70 min ', linestyle='--', linewidth=l_w_2) #ax1.plot(x_plot,new_y_extrapolation_2 , color=color_set[7], linestyle='--', linewidth=l_w_2) #SECOND NEW EXTRAPOLATION m=44 #decide which time step x_plot = np.linspace(1.5,6,100) #alberto print 'FIT IS AT TIMESTEP', several_times[m] #using new interpretation of b new_y_extrapolation_2=np.exp(c_fixed+(b_solved[m])*(x_plot-x_zero)-(1/(2*several_sigma_square_new[m])*(x_plot-x_zero)**2)) #ax1.plot(x_plot,new_y_extrapolation_2 , color=color_set[7], label=r'Extrapol t$\,\approx\,$400 min ', linestyle='--', linewidth=l_w_2) #ax1.plot(x_plot,new_y_extrapolation_2 , color=color_set[7], linestyle='--', linewidth=l_w_2) ###################################################################### #WRITE FILE WITH EXTRAPOLATION ###################################################################### extra_steps = np.arange(1.6,5,0.05) steps_y_extrapolation=np.exp(c_fixed+(b_solved[m])*(extra_steps-x_zero)-(1/(2*several_sigma_square_new[m])*(extra_steps-x_zero)**2)) #print interval3[32] # point at which interval is at 1.6 #print all_data3_3[0:32,35] write_interval=interval3 write_mass= np.concatenate((all_data3_3[0:32,35],steps_y_extrapolation)) #save scaled real data f = open('scaled_particle_pdf2000','w') for i in range(0,100): f.write('%4s %5s\n' %(write_interval[i], all_data3_3[i,19])) f.close() #f = open('extrapol_471min','w') #for i in range(0,100): # f.write('%4s %5s\n' %(write_interval[i], write_mass[i])) #f.close() ######################################################################## #PLOT PROPERTIES ######################################################################## begin_pos=s_point print 'mean is set to', interval3[begin_pos] #GRID LINES #axes = plt.gca() #axes.grid(True) ax1.set_yscale('symlog') # log y axis ax1.set_xlabel(r'$(M -G_ct)/M_r $', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt ax1.set_ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font) #ax1.set_xlim(0.1,3) ax1.set_xlim(0,3.2) ax1.set_ylim([10**2,1*10**7]) #Hide the right and top spines ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) #Only show ticks on the left and bottom spines ax1.yaxis.set_ticks_position('left') ax1.xaxis.set_ticks_position('bottom') ax1.legend(loc=1, frameon=False, numpoints=1) #position of legend ################################## #RADIUS FOR TOP AXIS ################################## # ax12 = ax1.twiny() # ax12.set_xlabel(r"Radius [$\mu m$]", fontsize=size_axes) # if (dycoms==0): # tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0] # tick_lbls = [8.2,10.3,11.8,13,14,14.9,15.7,16.4] # else: # tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0] # tick_lbls = [8.9,11,12.8,14,15.2,16.1,17,17.7] # # ax12.set_xticks(tick_locs) # ax12.set_xticklabels(tick_lbls) # ax12.set_xlim(0.1,4) # CHANGE POSITON OF A LEGEND #handles, labels = ax1.get_legend_handles_labels() #dummy_legend_h=handles[0] #dummy_legend_l=labels[0] #handles[0] = handles[len(handles)-1] #labels[0] = labels[len(labels)-1] #handles[len(handles)-1] = dummy_legend_h #labels[len(labels)-1] = dummy_legend_l #ax1.legend(handles, labels,loc=1, frameon=False, numpoints=1) # ######################################################################## # #plot a with time # ######################################################################## # # fig, ax2 = ppl.subplots() # plt.title('fit parameter a') # ax2.set_yscale('symlog') # # ax2.plot(write_interval,write_mass , color=color_set[9], label=r'Extrapolation t$\,\approx\,$70 min ', linestyle='--', linewidth=l_w_2) # ax2.plot(steps_time,a_new, color=color_set[5],marker='.',linestyle='None',markersize=m_s+9 ) ## ax2.plot(time_extrapol,a_fit , color=color_set[5],linestyle='--', linewidth=l_w_2) # # # ######################################################################## # #plot b with time # ######################################################################## # # fig, ax3 = ppl.subplots() # # plt.title('amount of particles in tail') # # ax3.plot(steps_time,N_integrate, color=color_set[3],marker='.',linestyle='None',markersize=m_s+9 ) ## ax3.plot(time_extrapol,test_b , color=color_set[3],linestyle='--', linewidth=l_w_2) # # ######################################################################## #plot sigma_square with time ######################################################################## # fig, ax4 = ppl.subplots() # # plt.title('fit parameter sigma square') # ax4.plot(steps_time,sigma_square_new, color=color_set[1],marker='.',linestyle='None',markersize=m_s+9 ) # ax4.plot(time_extrapol,sigma_square_new_fit , color=color_set[7],linestyle='--', linewidth=l_w_2) # # # ######################################################################## # #plot m_max with time # ######################################################################## # # fig, ax5 = ppl.subplots() # # plt.title('new interpretation of b') #ax5.set_xlim(0.1,3.5) # # ax5.plot(several_times,b_solved, color=color_set[1],marker='.',linestyle='None',markersize=m_s+9 ) plt.show()
def several_fits(all_interval3, all_data3_3, names3, p_title3, time_real_1,time_real_2,time_real_3, delta_s,t_real, time_data, dycoms, fitting, s_point): #SETUP COLORS FOR PLOTTING fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors #scale data if (dycoms == 0): all_data3_3=all_data3_3*50/18*0.92 else: all_data3_3=all_data3_3*30/18*1.75 #DECIDE ABOUT PLOTTING STEPS time_real_data=np.zeros(len(time_data)) for i in np.arange(len(time_data)): time_real_data[i]=round(time_data[i]*t_real/60,2) if (dycoms==0): steps=[9, 14, 22, 35] else: steps=[10, 20, 28, 35] c=1 #for color code #CONSTRUCT DATA FROM WHERE TO FIT (TAIL) AND PLOT DIFFERENT STEPS for k in steps: label_name='t=' + str(time_real_data[k]) + ' [min]' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[c],linewidth=l_w_1, label=label_name) log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(all_data3_3[:,k])): if (all_data3_3[i,k] != 0): log_data[i] = np.log(all_data3_3[i,k]) elif (all_data3_3[i,k] == 0): log_data[i]=all_data3_3[i,k] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break #CONSTRUCT FITS FOR SIMULATION STEPS z = np.polyfit(all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1], 2) print 'point where fitting starts', all_interval3[s_point,k], np.exp(log_data[s_point]) print 'polyfit',z p = np.poly1d(z) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) x = np.linspace(0,mean+6,1000) print 'mean and sigma_square', mean, sigma_square y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) print x[210] ax.plot(x[0:len(x)],y[0:len(y)] , color=color_set[c], linestyle='--', linewidth=l_w_2) c=c+2 #for color code #PLOTTING PROPERTIES ax.set_yscale('symlog') plt.xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font) if(dycoms==0): plt.xlim(1.4,2.7) else: plt.xlim(1.4,2.3) plt.ylim([10,5*10**6]) plt.legend(loc=1, frameon=False) plt.show()
avg5_time=avg5_time*50/60 avg6_time=avg6_time*50/60 else: data_name='profile/dy_re800_general_avg_5s.dat' avg5_x, avg5_y = np.loadtxt(data_name, unpack=True) data_name='profile/dy_re800_general_avg_6s.dat' avg6_x, avg6_y = np.loadtxt(data_name, unpack=True) ######################################################################## #PLOT ######################################################################## fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors if (diff == 1): ax.plot(avg5_time,avg5_value , color=color_set[3], label='Parcel Liquid', linestyle='-',linewidth=l_w_1) ax.plot(avg6_time,avg6_value , color=color_set[5], label='Droplet Liquid', linestyle='-',linewidth=l_w_1) else: avg5_x[:]=avg5_x[:]/np.max(avg5_x) avg6_x[:]=avg6_x[:]/np.max(avg6_x) ax.plot(avg5_y,avg5_x, color=color_set[3], label='Parcel Liquid', linestyle='-',linewidth=l_w_1) ax.plot(avg6_y,avg6_x , color=color_set[5], label='Droplet Liquid', linestyle='-',linewidth=l_w_1) #plt.xlim(0.9,2.6) if (diff == 1):
def scatter(original, updated, main="", save=None): """Plot a scatterplot of updated bitscores vs. original bitscores """ #Remove hits with no improvement and calcate the number of hits with no #improvement(udated == original), positive imporvent (updated > original), #and negative improvment (updated < original) print len(original) positiveImprovement = [] negativeImprovement = [] noImprovement = 0 for o, u in izip(original, updated): if int(o) == int(u): noImprovement +=1 elif u > o: positiveImprovement.append((o,u)) elif u < o: negativeImprovement.append((o,u)) else: noImprovement +=1 if not positiveImprovement: positiveImprovement = [()] if not negativeImprovement: negativeImprovement = [()] print positiveImprovement print negativeImprovement print noImprovement #Set deimensions x, y = zip(*positiveImprovement+negativeImprovement) xMax = int(round(sorted(x)[-1]/500.0)*500.0) yMax = int(round(sorted(y)[-1]/500.0)*500.0) sep = 500 xticks = range(0, xMax, sep) yticks = range(0,yMax,sep) color_cycle = brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors fig, ax = plt.subplots() ax.set_title(main) ax.set_xlabel("Original Bitscores") ax.set_ylabel("Updated Bitscores") #Plot postive improvement (green, automatically by prettyplotlib) if positiveImprovement: ppl.scatter(ax, *zip(*positiveImprovement), label="Positive Improvement ({} seqs)".format(len(positiveImprovement)), color=color_cycle[0]) #Draw no improvement line ppl.plot(ax, (0,xMax), (0,xMax), color='k', linestyle='-', linewidth=2, label="No Improvement ({} seqs)".format(noImprovement)) #Plot negative improvement (red, automatically by prettyplotlib) if negativeImprovement: ppl.scatter(ax, *zip(*negativeImprovement), label="Negative Improvement ({} seqs)".format(len(negativeImprovement)), color=color_cycle[1]) #Draw labels ppl.legend(ax) #Set axis ax.set_ylim([0,yMax]) ax.set_xlim([0,xMax]) if save is None: plt.show() else: pp = PdfPages(save) pp.savefig(fig) pp.close()
def several_times_and_flight(all_interval3, all_data3_3, names3, p_title3, time_real_1,time_real_2,time_real_3, delta_s,t_real, time_data, dycoms, fitting, s_point, interval_flight, data_flight,data3_3, interval3): #setup colors fig, ax1 = plt.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors shape= np.shape(all_interval3) time_length=shape[1] #scale data all_data3_3=all_data3_3*50/18*0.92 ######################################################################## #Plot the flight data ######################################################################## data_flight=data_flight*2.25*10**7#alberto #data_flight=data_flight*5.0*10**7 #ax1.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 , label='Flight measurements') #alberto #ax1.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 ) ax1.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 , label='Flight measurements') ######################################################################## #Plot the data+fit ######################################################################## time_real_data=np.zeros(len(time_data)) for i in np.arange(len(time_data)): time_real_data[i]=round(time_data[i]*t_real/60,2) #print time_real_data #steps=np.array([12,23, 35]) steps= np.arange(12,36) print 'here steps', steps c=1 l=0 b_new = np.zeros(len(steps)) a_new = np.zeros(len(steps)) sigma_square_new = np.zeros(len(steps)) x_max = np.zeros(len(steps)) for k in steps: time_real_data[k]=round(time_real_data[k],0) label_name='t=' + str(int(time_real_data[k])) + ' min' #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[c],linewidth=l_w_1, label='Simulation ' + label_name) #alberto #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[c],linewidth=l_w_1) if (k==12): #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1) ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name) elif (k==35): #ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1) ax1.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label='Simulation ' + label_name) log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(all_data3_3[:,k])): if (all_data3_3[i,k] != 0): log_data[i] = np.log(all_data3_3[i,k]) elif (all_data3_3[i,k] == 0): log_data[i]=all_data3_3[i,k] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break #POLYNOMIAL FIT z = np.polyfit(all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1], 2) #print 'point where fitting starts', all_interval3[s_point,k], np.exp(log_data[s_point]) #print 'polyfit',z p = np.poly1d(z) #ax1.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) #x = np.linspace(0,mean+6,1000) x = np.linspace(1.75,mean+6,1000) #alberto #print 'FIT: mean and sigma_square', mean, sigma_square #print 'k', k y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) #print x[210] #ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[c], linestyle='--', linewidth=l_w_2) if (k==12): ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[1], linestyle='--', linewidth=l_w_2) elif (k==35): ax1.plot(x[0:len(x)],y[0:len(y)] , color=color_set[1], linestyle='--', linewidth=l_w_2) c=c+2 #CURVE FITTIN x_zero=1.75 def pol_func(x,a,b,c): return a*(x-x_zero)**2+b*(x-x_zero)+c #return a*(x)**2+b*(x)+c fitpars, covmat = so.curve_fit(pol_func,all_interval3[s_point:end_pos+1,k], log_data[s_point:end_pos+1]) mean_new=fitpars[1]/(-2*fitpars[0]) sigma_square_calc=(1/(-2*fitpars[0])) #NEW Y WITH x=x-x_zero c_fixed=13.2 y_new=np.exp( (c_fixed+fitpars[1]**2/(4*-fitpars[0]))-((((x-x_zero)-mean_new)**2)/(2*sigma_square_calc)) ) print 'CURVE FIT fitpars', fitpars print 'CURVE FIT corresponding mean and sigma', mean_new, sigma_square_calc #ax1.plot(x[0:len(x)],y_new[0:len(y)] , color=color_set[7], linestyle='--', linewidth=l_w_2-3) a_new[l]=fitpars[0] b_new[l]=fitpars[1] x_max[l]=x_zero-b_new[l]/(2*a_new[l]) sigma_square_new[l]=-1/(2*fitpars[0]) l=l+1 #LINEAR FIT FOR a AND x_max FOR b def lin_func(x,a,b): return a*(x)+b def pol2_func(x,a,b,c): return a*(x)**2+b*x+c def tanh_func(x,a,b,c): return c+a*np.tanh(x+b) def sqrt_func(x,a,b,c): return c+a*np.sqrt(x+b) def asympt_func(x,a,b,c): return c+b/x+a/(x**2) #fitpars_2, covmat_2 = so.curve_fit(lin_func,steps,a_new) fitpars_2, covmat_2 = so.curve_fit(asympt_func,steps,a_new) #fitpars_2, covmat_2 = so.curve_fit(tanh_func,steps,a_new) #fitpars_2, covmat_2 = so.curve_fit(sqrt_func,steps,a_new) #fitpars_2, covmat_2 = so.curve_fit(pol2_func,steps,a_new) fitpars_3, covmat_3 = so.curve_fit(lin_func,steps,x_max) #fitpars_3, covmat_3 = so.curve_fit(pol2_func,steps,x_max) fitpars_4, covmat_3 = so.curve_fit(lin_func,steps,b_new) fitpars_5, covmat_3 = so.curve_fit(lin_func,steps,sigma_square_new) time_part=np.arange(0,len(time_real_3)) fitpars_time, covmat_3 = so.curve_fit(lin_func,time_part,time_real_3) #USING ACTUAL FIT FOR time x = np.linspace(5,90,100) time_extrapol=fitpars_time[0]*x+fitpars_time[1] steps_time=fitpars_time[0]*steps+fitpars_time[1] #USING ACTUAL FIT FOR x_max x_max_fit = fitpars_3[0]*x+fitpars_3[1] #x_max_fit = fitpars_3[0]*x**2+fitpars_3[1]*x+fitpars_3[2] #USING ACTUAL FIT FOR b test_b = fitpars_4[0]*x+fitpars_4[1] #USING ACTUAL FIT FOR a #a_fit = fitpars_2[0]*x+fitpars_2[1] a_fit = fitpars_2[0]*(1.0/x**2)+fitpars_2[1]*(1.0/x)+fitpars[2] #a_fit = fitpars_2[2]+fitpars_2[0]*np.tanh(x+fitpars_2[1]) #a_fit = fitpars_2[2]+fitpars_2[0]*np.sqrt(x+fitpars_2[1]) #a_fit = fitpars_2[0]*x**2+fitpars_2[1]*x + fitpars_2[2] #USING ACTUAL FIT FOR b sigma_square_new_fit = fitpars_5[0]*x+fitpars_5[1] #SEVERAL TIME STEPS several_x = np.array([30, 35, 50 ,60 ,70 ,80,100,120, 250]) several_times=fitpars_time[0]*several_x+fitpars_time[1] several_x_max = fitpars_3[0]*several_x+fitpars_3[1] #several_x_max = fitpars_3[0]*several_x**2+fitpars_3[1]*several_x+fitpars_3[2] several_test_b = fitpars_4[0]*several_x+fitpars_4[1] #several_a = fitpars_2[0]*several_x+fitpars_2[1] several_a = fitpars_2[0]*(1.0/several_x**2)+fitpars_2[1]*(1.0/several_x)+fitpars_2[2] #several_a = fitpars_2[2]+fitpars_2[0]*np.tanh(several_x+fitpars_2[1]) #several_a = fitpars_2[2]+fitpars_2[0]*np.sqrt(several_x+fitpars_2[1]) #several_a = fitpars_2[0]*several_x**2+fitpars_2[1]*several_x +fitpars_2[2] several_sigma_square_new = fitpars_5[0]*several_x+fitpars_5[1] several_b = (several_x_max-x_zero)*(-2*several_a) print 'several times', several_times print 'corresponding x_max', several_x_max print 'corresponding a', several_a print 'calculated b', several_b print 'test b', several_test_b print 'several_sigma_new', several_sigma_square_new #NEW EXTRAPOLATION m=8 x_plot = np.linspace(1.75,6,100) #alberto #new_mean=-several_test_b[m]/(2*several_a[m]) #new_mean=several_test_b[m]*sigma_square_new[m] #new_mean=x_zero-several_b[m]/(2*several_a[m]) new_sigma=(1/(-2*several_a[m])) #c_calc=np.log(1/(np.sqrt(several_sigma_square_new[m])*sqrt(2*3.14))) #new_y_extrapolation=np.exp(13+several_test_b[m]**2/(4*several_a[m])+several_test_b[m]*(x_plot-x_zero)+several_a[m]*(x_plot-x_zero)**2) #new_y_extrapolation=np.exp(13+several_test_b[0]*(x_plot-x_zero)+several_a[m]*(x_plot-x_zero)**2) #with direct b new_y_extrapolation=np.exp(13+several_test_b[0]*(x_plot-x_zero)-(1/(2*several_sigma_square_new[m])*(x_plot-x_zero)**2)) #indirect b new_y_extrapolation_2=np.exp(13+(-2)*(x_plot-x_zero)-(1/(2*several_sigma_square_new[m])*(x_plot-x_zero)**2)) ax1.plot(x_plot,new_y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$80 min ', linestyle='--', linewidth=l_w_2) ax1.plot(x_plot,new_y_extrapolation_2 , color=color_set[7], label=r'Extrapolation t$\,\approx\,$80 min ', linestyle='--', linewidth=l_w_2) ######################################################################## #use one of the latest time-steps to extrapolate data ######################################################################## data3_3=data3_3*50/18*0.92 log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data3_3)): if (data3_3[i] != 0): log_data[i] = np.log(data3_3[i]) elif (data3_3[i] == 0): log_data[i]=data3_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break begin_pos=s_point print 'mean is set to', interval3[begin_pos] #print 'end_pos', end_pos z = np.polyfit(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], 2) #print 'polyfit',z p = np.poly1d(z) #ax1.plot(interval3[begin_pos:end_pos+1], np.exp(log_data[begin_pos:end_pos+1]), '.', color=color_set[5],linewidth=l_w_1, label='Fitting points' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) #for 30min=0.434 40min=0.586 and 50min=0.74 #attetntion we will use growing**2 #growing=[0.2, 0.434, 0.586, 0.74] #growing=[0.53]#alberto #growing=[0.74]#50 min growing=[0.21, 0.434, 0.74] #growing=[0.21, 0.434, 0.74, 0.9, 1.2] #l=0 #M_max_all= np.zeros(len(growing)) #test= np.zeros(len(growing)) sigma_extrapolation_all= np.zeros(len(growing)) for k in np.arange(len(growing)): sigma_extrapolation=growing[k]**2 #after certain time a=-1/(2*sigma_extrapolation) #only for testing #mean_extrapolation=z[1]/(-2*a) #only for testing #x = np.linspace(0,mean+6,1000) x = np.linspace(1.75,mean+6,1000) #alberto print 'EXTRAPOLATION: mean and sigma_square_extra', mean, sigma_extrapolation #OLD extrapolation #y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) y_extrapolation=np.exp( 1/(growing[k]*np.log(2*3.14))-(((x-mean)**2)/(2*sigma_extrapolation)) ) #M_max=-(z[1]/(2*a)) #M_max_all[l]=M_max #sigma_extrapolation_all[l]=sigma_extrapolation #print 'M_max verschiebung', M_max ##test[l]=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((M_max-mean)**2)/(2*sigma_extrapolation)) ) #test[l]=a*x**2+z[1]+z[2] #print 'test', test[l] #print 'a and b', a, z[1] # #l=l+1 ###if (k==0): ###ax1.plot(x,y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$30 \& 50 [min] ', linestyle='--', linewidth=l_w_2) #alberto #ax1.plot(x,y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$60 min ', linestyle='--', linewidth=l_w_2) ###ax1.plot(x,y_extrapolation , color=color_set[5], linestyle='--', linewidth=l_w_2) ###elif (k==1): ###ax1.plot(x,y_extrapolation , color=color_set[5], linestyle='--', linewidth=l_w_2) #ax1.plot(x,y_extrapolation , color=color_set[5], linestyle='--', linewidth=l_w_2) #GRID LINES axes = plt.gca() axes.grid(True) ax1.set_yscale('symlog') #ax1.set_xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt #alberto ax1.set_xlabel('Droplet mass', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt ax1.set_ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font) #ax1.set_xticks([0.1,0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]) #ax1.set_xlim(1.5,5) ax1.set_xlim(0.8,4)#alberto ax1.set_ylim([10**2,10**8]) # ax12 = ax1.twiny() # ax12.set_xlabel(r"Radius [$\mu m$]", fontsize=size_axes) if (dycoms==0): tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0] tick_lbls = [8.2,10.3,11.8,13,14,14.9,15.7,16.4] else: tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0] tick_lbls = [8.9,11,12.8,14,15.2,16.1,17,17.7] # ax12.set_xticks(tick_locs) # ax12.set_xticklabels(tick_lbls) # ax12.set_xlim(0.1,3) ax1.legend(loc=0, frameon=False) plt.legend(loc=1, frameon=False) ######################################################################## #plot a with time ######################################################################## fig, ax2 = ppl.subplots() ax2.plot(steps_time,a_new, color=color_set[5],marker='.',linestyle='None',markersize=m_s+9 ) ax2.plot(time_extrapol,a_fit , color=color_set[5],linestyle='--', linewidth=l_w_2) ######################################################################## #plot b with time ######################################################################## fig, ax3 = ppl.subplots() ax3.plot(steps_time,b_new, color=color_set[3],marker='.',linestyle='None',markersize=m_s+9 ) ax3.plot(time_extrapol,test_b , color=color_set[3],linestyle='--', linewidth=l_w_2) ######################################################################## #plot sigma_square with time ######################################################################## fig, ax4 = ppl.subplots() ax4.plot(steps_time,sigma_square_new, color=color_set[1],marker='.',linestyle='None',markersize=m_s+9 ) ax4.plot(time_extrapol,sigma_square_new_fit , color=color_set[7],linestyle='--', linewidth=l_w_2) ######################################################################## #plot m_max with time ######################################################################## #fig, ax5 = ppl.subplots() #ax5.plot(steps_time,x_max, color=color_set[7],marker='.',linestyle='None',markersize=m_s+9 ) #ax5.plot(time_extrapol,x_max_fit , color=color_set[7],linestyle='--', linewidth=l_w_2) plt.show()
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Mar 5 17:09:19 2018 @author: dawlat_local """ import pandas import matplotlib.pyplot as plt from prettyplotlib import brewer2mpl import prettyplotlib as ppl from matplotlib.backends.backend_pdf import PdfPages set2 = brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors set1 = brewer2mpl.get_map('Set1', 'qualitative', 9).mpl_colors bmap = brewer2mpl.get_map('Dark2', 'Qualitative', 4).mpl_colors mpl.rcParams['axes.color_cycle'] = bmap # scored csv patient_scored = pandas.read_csv('') test_df = patient_scored.loc[:, 'subj_id':'trial7'].dropna() pt_all_trials = pandas.DataFrame(data=patient_scored.set_index( 'subj_id').loc[:, 'trial1':'trial7']).dropna().astype(int) pt_learning_trials = pandas.DataFrame(data=patient_scored.set_index( 'subj_id').loc[:, 'trial1':'trial5']).dropna().astype(int) # tp1 tp2 composite scores comp = ['total_learning', 'corrected_total_learning', 'learning_rate', 'proactive_interference', 'retroactive_interference', 'forgetting_and_retention'] comp_2 = ['total_learning_2', 'corrected_total_learning_2', 'learning_rate_2',
def test_pcolormesh_other_cmap(): purple_green = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap np.random.seed(10) ppl.pcolormesh(np.random.randn(10, 10), cmap=purple_green)
def extrapolation_sigma(all_interval1, all_data1_3, all_interval2, all_data2_3, all_interval3, all_data3_3, names3, p_title3, time_real_1,time_real_2,time_real_3,delta_s,t_real, dycoms): close='all' fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors #DATA RE800 shape= np.shape(all_interval1) time_length=shape[1] data1_3= np.zeros(100) interval1= np.zeros(100) sigma_vector_1= np.zeros(time_length) for k in np.arange(time_length): data1_3[:] = all_data1_3[:,k] interval1[:] = all_interval1[:,k] log_data= np.zeros(100) for i in np.arange(len(data1_3)): if (data1_3[i] != 0): log_data[i] = np.log(data1_3[i]) elif (data1_3[i] == 0): log_data[i]=data1_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval1[24:end_pos+1], log_data[24:end_pos+1], 2) sigma_square=(1/(-2*z[0])) sigma_vector_1[k]= np.sqrt(sigma_square) sigma_fit_1 = np.polyfit(time_real_1, sigma_vector_1, 1) ax.plot(time_real_1,sigma_vector_1 , color=color_set[3],linewidth=2, label='Data Re800') x_fit = np.linspace(0,60,1000) p = sigma_fit_1[0]*x_fit + sigma_fit_1[1] #p = sigma_fit_2[0]*x_fit**2 + sigma_fit_2[1]*x_fit + sigma_fit_2[2] # if (dycoms != 0): # ax.plot(x_fit,p ,linestyle='--', color=color_set[2], label='Fiting', linewidth=2) #DATA RE400 shape= np.shape(all_interval2) time_length=shape[1] data2_3= np.zeros(100) interval2= np.zeros(100) sigma_vector_2= np.zeros(time_length) for k in np.arange(time_length): data2_3[:] = all_data2_3[:,k] interval2[:] = all_interval2[:,k] log_data= np.zeros(100) for i in np.arange(len(data2_3)): if (data2_3[i] != 0): log_data[i] = np.log(data2_3[i]) elif (data2_3[i] == 0): log_data[i]=data2_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval2[24:end_pos+1], log_data[24:end_pos+1], 2) sigma_square=(1/(-2*z[0])) sigma_vector_2[k]= np.sqrt(sigma_square) sigma_fit_2 = np.polyfit(time_real_2, sigma_vector_2, 1) ax.plot(time_real_2,sigma_vector_2 , color=color_set[5],linewidth=2, label='Data Re400') x_fit = np.linspace(0,60,1000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] #p = sigma_fit_2[0]*x_fit**2 + sigma_fit_2[1]*x_fit + sigma_fit_2[2] # if (dycoms != 0): # ax.plot(x_fit,p ,linestyle='--', color=color_set[4], label='Fitting', linewidth=2) if (dycoms == 0): #DATA RE200 shape= np.shape(all_interval3) time_length=shape[1] data3_3= np.zeros(100) interval3= np.zeros(100) sigma_vector= np.zeros(time_length) print sigma_vector[9] c= np.zeros(time_length) for k in np.arange(time_length): data3_3[:] = all_data3_3[:,k] interval3[:] = all_interval3[:,k] log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data3_3)): if (data3_3[i] != 0): log_data[i] = np.log(data3_3[i]) elif (data3_3[i] == 0): log_data[i]=data3_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval3[24:end_pos+1], log_data[24:end_pos+1], 2) sigma_square=(1/(-2*z[0])) sigma_vector[k]= np.sqrt(sigma_square) sigma_fit = np.polyfit(time_real_3, sigma_vector, 1) print 'sigma_fit', sigma_fit x_fit = np.linspace(0,60,1000) #p = sigma_fit[0]*x_fit**2 + sigma_fit[1]*x_fit + sigma_fit[2] p = sigma_fit[0]*x_fit + sigma_fit[1] ax.plot(time_real_3,sigma_vector , color=color_set[1],linewidth=2, label='Data Re200') ax.plot(x_fit,p , color=color_set[0],linestyle='--', linewidth=2, label='Fitting') tau=t_real/delta_s print len(time_real_3), len(sigma_vector) for l in np.arange(len(time_real_3)): c[l] = sigma_vector[l]*tau/time_real_3[l] print np.mean(c), sigma_fit[0] #p_test=np.mean(c)*x_fit #ax.plot(x_fit,p_test ,color=color_set[9],linewidth=2, label='bla') #GENERAL PLOT SETTINGS # if(dycoms == 0): # plt.title(r'VERDI - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font) # else: # plt.title(r'DYCOMS-II - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font) plt.xlabel('t [min]')#, fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel(r'\textbf{$\sigma$}')#, fontsize=size_axes)#,fontdict=font) #plt.xlim(0,4) plt.ylim(0) plt.legend(loc=2, frameon=False) plt.show()
# t = timeit.Timer("libprimes.%(pgen)s(n)" % locals(), setup=config) t = timeit.Timer("%(pgen)s(n)" % locals(), setup=config) # execute = timeit.Timer("libprimes.%(pgen)s(n)" % locals(), setup=config) execute = timeit.Timer("%(pgen)s(n)" % locals(), setup=config) execute_times = t.repeat(repeat=nb_benchloop, number=1) benchtime = np.mean(execute_times) benchtimes.append(benchtime) print('.', end='', flush=True) results[pgen] = {'benchtimes': np.array(benchtimes)} print('') print(datetime.datetime.now().strftime(datetimeformat)) fig, ax = plt.subplots(1) plt.ylabel('Computation time (in miliseconds)') plt.xlabel('N') plt.xscale('log') plt.yscale('log') set2 = brewer2mpl.get_map('Paired', 'qualitative', 12).mpl_colors i = 0 for pgen in primenumbers_gen: bench = results[pgen]['benchtimes'] * 1000 i += 1 label = "%(pgen)s avg" % locals() ppl.plot(nbs, bench, label=label, lw=2, color=set2[i % 12]) ppl.legend(ax, loc='upper left', ncol=4) fig.canvas.draw() ax = plt.gca() plt.grid() plt.show()
def plot_data_compare_2(interval1,data1_1, data1_2, data1_3, interval2, data2_1, data2_2, data2_3, interval3, data3_1, data3_2, data3_3, interval_flight, data_flight, names1, style, p_title1, names2, p_title2, names3, p_title3, dycoms,extrapolation,extrapolation_2 , fitting,flight, only_last, s_point): close='all' if ( style == 0): #COLORS FOR PLOTTING fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors #!!!!!!!!!!!!! #General #!!!!!!!!!!!!! # ax.plot(interval1,data1_1, color='black', linewidth=l_w_1,label=names1[1]) # ax.plot(interval1,data1_2, color='red', linewidth=l_w_1,label=names1[2]) # ax.plot(interval1,data1_3, color='blue',linestyle='-', label=names1[3]) if (only_last !=1): #ax.plot(interval1,data1_3, color=color_set_2[8],linewidth=l_w_1, label=names1[3]) ax.plot(interval1,data1_3, color=color_set[1],linewidth=l_w_1, label=names1[3]) if (dycoms ==0): data2_1=data2_1*30/18*1.3 data2_2=data2_2*30/18*1.3 data2_3=data2_3*30/18*1.3 else: data2_1=data2_1*30/18*1.75 data2_2=data2_2*30/18*1.75 data2_3=data2_3*30/18*1.75 # ax.plot(interval2,data2_1, color='red',linestyle='-', linewidth=l_w_1,label=names2[1]) # ax.plot(interval2,data2_2, color='black',linestyle='-', linewidth=l_w_1, label=names2[2]) if (dycoms==1): if (only_last !=1): #ax.plot(interval2,data2_3, color=color_set_2[6],linewidth=l_w_1, label=names2[3]) ax.plot(interval2,data2_3, color=color_set[3],linewidth=l_w_1, label=names2[3]) else: ax.plot(interval2,data2_3, color=color_set[1],linewidth=l_w_1, label=names2[3]) else: # ax.plot(interval2,data2_3, color=color_set_2[6],linewidth=l_w_1, label=names2[3]) if (only_last !=1): ax.plot(interval2,data2_3, color=color_set[3],linewidth=l_w_1, label=names2[3]) if (dycoms==0): data3_1=data3_1*50/18*1.4 # add the scaling factor data3_2=data3_2*50/18*1.4 data3_3=data3_3*50/18*1.4 #ax.plot(interval3,data3_1, color='black',linestyle='-',linewidth=l_w_1, label=names3[1]) #ax.plot(interval3,data3_2, color='red',linestyle='-',linewidth=l_w_1, label=names3[2]) #ax.plot(interval3,data3_3,color=color_set_2[4],linewidth=l_w_1, label=names3[3]) if (only_last !=1): ax.plot(interval3,data3_3,color=color_set[5],linewidth=l_w_1, label=names3[3]) else: if( flight ==0): ax.plot(interval3,data3_3,color=color_set[1],linewidth=l_w_1, label=names3[3]) #!!!!!!!!!!!!! #Fitting #!!!!!!!!!!!!! if (dycoms ==0): log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data3_3)): if (data3_3[i] != 0): log_data[i] = np.log(data3_3[i]) elif (data3_3[i] == 0): log_data[i]=data3_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break begin_pos=s_point print 'mean is set to', interval3[begin_pos] print 'end_pos', end_pos z = np.polyfit(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], 2) print 'polyfit',z p = np.poly1d(z) #ax.plot(interval3[begin_pos:end_pos+1], np.exp(log_data[begin_pos:end_pos+1]), '.', color=color_set[5],linewidth=l_w_1, label='Fitting points' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) #VERDI if( flight ==0): sigma_extrapolation=0.545**2 #after 40 min else: #sigma_extrapolation=0.764**2 #after 50 min sigma_extrapolation=0.74**2 #after 50 min #sigma_extrapolation=0.91**2 #after 60 min a=-1/(2*sigma_extrapolation) mean_extrapolation=z[1]/(-2*a) x = np.linspace(0,mean+6,1000) print 'mean and sigma_square', mean, sigma_square y_log=( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) if (flight != 1): #no fligh data if (fitting == 1): #if we want fit ax.plot(x,y , color=color_set_3[0], label='Gaussian fit', linestyle='--', linewidth=l_w_2) if (extrapolation == 1): #if we want extrapolation if( flight ==0): #if we want no fligh data ax.plot(x,y_extrapolation , color=color_set[5], label='Extrapolation t=40', linestyle='--', linewidth=l_w_2) if(extrapolation_2==1): #if we want second extrapolation #extrapolation for all times growing=[0.91, 1.80, 5.37, 10.7, 21.4] for k in np.arange(len(growing)): sigma_extrapolation=growing[k]**2 print sigma_extrapolation x = np.linspace(0,mean+115,1000) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) ax.plot(x,y_extrapolation , color=color_set[k], linestyle='--',linewidth=l_w_2) else: #if we want extrapolation with flight data together ax.plot(x,y_extrapolation , color=color_set[5], label=r'Extrapolation t$\,\approx\,$50 [min]', linestyle='--', linewidth=l_w_2) #SCALE FLIGHT DATA data_flight=data_flight *5.5*10**7 if (flight == 1): ax.plot(interval_flight,data_flight, color=color_set[9],marker='.',linestyle='None',markersize=m_s+9 , label='Flight measurements') else: #if we want DYCOMS instead of verdi log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data2_3)): if (data2_3[i] != 0): log_data[i] = np.log(data2_3[i]) elif (data2_3[i] == 0): log_data[i]=data2_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval2[s_point:end_pos+1], log_data[s_point:end_pos+1], 2) print 'polyfit',z p = np.poly1d(z) #ax.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) #DYCOMS sigma_extrapolation=0.525**2 a=-1/(2*sigma_extrapolation) mean_extrapolation=z[1]/(-2*a) print sigma_extrapolation x = np.linspace(0,mean+6,1000) print 'mean and sigma_square', mean, sigma_square y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) if (fitting == 1): ax.plot(x,y , color=color_set_3[0], label='Gaussian fit', linestyle='--', linewidth=l_w_2) if (extrapolation == 1): ax.plot(x,y_extrapolation , color=color_set[5], label='Extrapolation t=40', linestyle='--',linewidth=l_w_2) if(extrapolation_2==1): #extrapolation for all times growing=[0.76, 1.49, 4.4, 8.75, 17.4] for k in np.arange(len(growing)): sigma_extrapolation=growing[k]**2 print sigma_extrapolation x = np.linspace(0,mean+100,1000) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) ax.plot(x,y_extrapolation , color=color_set[k], linestyle='--',linewidth=l_w_2) #!!!!!!!!!!!!! #Plotting #!!!!!!!!!!!!! #GRID LINES #axes = plt.gca() #axes.grid(True) ax.set_yscale('symlog') # if (dycoms ==0): # plt.title(p_title3, fontsize=size_title)#,fontdict=font) # else: # plt.title(p_title2, fontsize=size_title)#,fontdict=font) plt.xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel('Relative amount of droplets', fontsize=size_axes)#,fontdict=font) if (extrapolation == 1): plt.xlim(0.9,5.2) plt.xlim(0.8,4.5) #plt.xlim(1.3,5.2) if(extrapolation_2==1): plt.xlim(0.9,115) elif(flight == 1): ax2 = ax.twiny() ax2.set_xlabel(r"Radius [$\mu m$]", fontsize=size_axes) tick_locs = [1,2,3,4,5] tick_lbls = [10.3,13,14.9,16.4,17.7] ax2.set_xticks(tick_locs) ax2.set_xticklabels(tick_lbls) #ax2.set_xlim(1.3,5.2) ax2.set_xlim(0.8,4.5) ax.legend(loc=0, frameon=False) elif(fitting == 1): plt.xlim(0.9,2.6) else: plt.xticks([0.1,0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]) plt.xlim(0.1,2.2) plt.ylim([10,10**8]) #plt.ylim([10**3,10**9]) #plt.xlim([0.9,3.0]) plt.legend(loc=1, frameon=False) #Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') plt.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from numpy.random import randn import matplotlib as mpl mpl.rcParams['font.family'] = 'Helvetica Neue' import prettyplotlib as ppl from prettyplotlib import brewer2mpl np.random.seed(64) set2 = brewer2mpl.get_map('Set2', 'qualitative', '8').mpl_colors color1, color2, color3, color4, color5 = set2[0], set2[1], set2[2], set2[3], set2[4] set3 = brewer2mpl.get_map('Set2', 'qualitative', '5').mpl_colors color6, color7, color8, color9, color10 = set3[0], set3[1], set3[2], set3[3], set3[4] p1 = brewer2mpl.get_map('Paired', 'Qualitative', 5).mpl_colors c1, c2, c3, c4, c5 = p1[0], p1[1], p1[2], p1[3], p1[4] p2 = brewer2mpl.get_map('Paired', 'Qualitative', 8).mpl_colors c6, c7, c8, c9, c10 = p2[0], p2[1], p2[2], p2[3], p2[4] p3 = brewer2mpl.get_map('Paired', 'Qualitative', 6).mpl_colors # standard c11, c12, c13, c14, c15 = p3[0], p3[1], p3[2], p3[3], p3[4] p4 = brewer2mpl.get_map('Pastel1', 'Qualitative', 6).mpl_colors c16, c17, c18, c19, c20 = p4[0], p4[1], p4[2], p4[3], p4[4] def main():
# smoothed = np.zeros((nbins-window_smoth,ntimes)) # for i in range(0,ntimes): ## smoothed_dummy = movingaverage(np.log(residence_lambda[:,i]),window_smoth) ## for j in range(0,nbins-window_smoth-1): ## smoothed[j,i] = smoothed_dummy[j+1] - smoothed_dummy[j] # for j in range(0,nbins-1): # #diff_residence_lambda[j,i] = np.log(scale_residence_lambda[j+1,i]) - np.log(scale_residence_lambda[j,i]) # diff_residence_lambda[j,i] = np.log(residence_lambda[j+1,i]) - np.log(residence_lambda[j,i]) # smoothed[:,i] = movingaverage(diff_residence_lambda[:,i],window_smoth) ######################################################################## # Plot data ######################################################################## fig, ax = plt.subplots() color_set = brewer2mpl.get_map("paired", "qualitative", 12).mpl_colors color_set_2 = brewer2mpl.get_map("PuBu", "sequential", 9).mpl_colors color_set_3 = brewer2mpl.get_map("Dark2", "qualitative", 8).mpl_colors color_set_4 = brewer2mpl.get_map("Pastel1", "qualitative", 9).mpl_colors t_inter = tstart / tstep print "t_intermediate", t_inter # Scaled data to plot list = [22, 32, 42, 54, 63, 74, 85] k = 0 for i in range(t_inter, len(time_real_data)): k = k + 1 # print time_real_data[i],k l_c = [2, 1, 0, 4, 5, 6, 7]
def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ import prettyplotlib as ppl from prettyplotlib import brewer2mpl from pymatgen.util.plotting_utils import get_publication_quality_plot ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allenergies = [] plt = get_publication_quality_plot(12, 8) # Note that this complicated processing of energies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): energies = dos['energies'] densities = dos['densities'] if not y: y = { Spin.up: np.zeros(energies.shape), Spin.down: np.zeros(energies.shape) } newdens = {} for spin in [Spin.up, Spin.down]: if spin in densities: if self.stack: y[spin] += densities[spin] newdens[spin] = y[spin].copy() else: newdens[spin] = densities[spin] allenergies.append(energies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allenergies.reverse() allpts = [] for i, key in enumerate(keys): x = [] y = [] for spin in [Spin.up, Spin.down]: if spin in alldensities[i]: densities = list(int(spin) * alldensities[i][spin]) energies = list(allenergies[i]) if spin == Spin.down: energies.reverse() densities.reverse() x.extend(energies) y.extend(densities) allpts.extend(list(zip(x, y))) if self.stack: plt.fill(x, y, color=colors[i % ncolors], label=str(key)) else: ppl.plot(x, y, color=colors[i % ncolors], label=str(key), linewidth=3) if not self.zero_at_efermi: ylim = plt.ylim() ppl.plot( [self._doses[key]['efermi'], self._doses[key]['efermi']], ylim, color=colors[i % ncolors], linestyle='--', linewidth=2) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) if self.zero_at_efermi: ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Energies (eV)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt
def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ import prettyplotlib as ppl from prettyplotlib import brewer2mpl from pymatgen.util.plotting_utils import get_publication_quality_plot ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allenergies = [] plt = get_publication_quality_plot(12, 8) # Note that this complicated processing of energies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): energies = dos['energies'] densities = dos['densities'] if not y: y = {Spin.up: np.zeros(energies.shape), Spin.down: np.zeros(energies.shape)} newdens = {} for spin in [Spin.up, Spin.down]: if spin in densities: if self.stack: y[spin] += densities[spin] newdens[spin] = y[spin].copy() else: newdens[spin] = densities[spin] allenergies.append(energies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allenergies.reverse() allpts = [] for i, key in enumerate(keys): x = [] y = [] for spin in [Spin.up, Spin.down]: if spin in alldensities[i]: densities = list(int(spin) * alldensities[i][spin]) energies = list(allenergies[i]) if spin == Spin.down: energies.reverse() densities.reverse() x.extend(energies) y.extend(densities) allpts.extend(list(zip(x, y))) if self.stack: plt.fill(x, y, color=colors[i % ncolors], label=str(key)) else: ppl.plot(x, y, color=colors[i % ncolors], label=str(key), linewidth=3) if not self.zero_at_efermi: ylim = plt.ylim() ppl.plot([self._doses[key]['efermi'], self._doses[key]['efermi']], ylim, color=colors[i % ncolors], linestyle='--', linewidth=2) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) if self.zero_at_efermi: ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Energies (eV)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt
# coding: utf-8 # In[10]: import numpy import scipy import time from scipy import stats import matplotlib as mpl import matplotlib.pyplot as plt import prettyplotlib as ppl from prettyplotlib import brewer2mpl set2 = brewer2mpl.get_map('Set2', 'qualitative', 8).mpl_colors mpl.rc('axes', color_cycle=set2) mpl.rc('axes', linewidth=3) mpl.rc('xtick', labelsize=20) mpl.rc('xtick.major', width=3) mpl.rc('xtick.major', size=10) mpl.rc('ytick', labelsize=20) mpl.rc('ytick.major', size=10) mpl.rc('ytick.major', width=3) mpl.rc('lines', linewidth=3) # In[11]: #Figure 4+5 Consolidated svbvds_id2 = zeros([10, 10, 2, 2]) for i in range(1, 20): filename = 'D:\\Po-Yi\\Grad\\yProgress\\1704\\AD\\Results0425\\Po_Yi_results\\svbvds_id2_rep_%d.npy' % i
def several_times_and_flight(all_interval3, all_data3_3, t_real, time_data, interval_flight, data_flight,interval_flight_2, data_flight_2, flight_err_2, data3_3, interval3): #setup colors and plot enviroment fig, ax1 = plt.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('YlGnBu', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors color_set_4 = brewer2mpl.get_map('Purples', 'sequential', 9).mpl_colors shape= np.shape(all_interval3) time_length=shape[1] #sum of all particles sum_all_data3_3 = np.zeros(time_length) for i in np.arange(time_length): sum_all_data3_3[i]=np.sum(all_data3_3[:,i]) sum_all_data3_3[i]=sum_all_data3_3[i]-all_data3_3[0,i] ######################################################################## #Plot the flight data ######################################################################## data_flight=data_flight*0.9*10**7 #change amount of particles accoding to simulation data_flight_2=data_flight_2*0.9*10**7 flight_err_2 = data_flight_2[:] * flight_err_2[:] #error data seems wrong #ax1.plot(interval_flight,data_flight,zorder=10, color=color_set_4[4],marker='.',linestyle='None',markersize=m_s+9 , label='Flight data') ax1.plot(interval_flight_2,data_flight_2,zorder=10, color=color_set_4[7],marker='.',linestyle='None',markersize=m_s+9 , label='Flight data') #if u need errorbars use this command #ax1.errorbar(interval_flight_2,data_flight_2,yerr=flight_err_2,zorder=10, color=color_set[8],marker='.',linestyle='None',markersize=m_s+9 , label='Flight data') ######################################################################## #Plot the data+fit ######################################################################## time_real_data=np.zeros(len(time_data)) for i in np.arange(len(time_data)): time_real_data[i]=round(time_data[i]*t_real/60,2) print 'real time',i,time_real_data[i] t_0 = 0 # timestep was before 55 G = 0.09/20 #cooling rate from tkstat plot_t = [59,82,107,133,159,186] #"timesteps" we want to plot #plot_t = [186] # only last step t_sim=time_data[plot_t[:]] #simulation time-step from time_data l_c = [0,1,2,3,4,5] # for colors of brewer color scale #l_c = [5] # red color j=0 #counter for colors for k in plot_t: time_real_data[k]=round(time_real_data[k],0) label_name='t=' + str(int(time_real_data[k])) + ' min' if (k < t_0 ): scale=0 else: scale = G*(t_sim[j]-t_0) ax1.plot(all_interval3[:,k]-scale,all_data3_3[:,k],color=color_set[l_c[j]],linewidth=l_w_1, label=label_name) j=j+1 #used for color ######################################################################## #PLOT PROPERTIES ######################################################################## #GRID LINES #axes = plt.gca() #axes.grid(True) ax1.set_yscale('symlog') # log y axis ax1.set_xlabel(r'$(M -G_ct)/M_r $', fontsize=size_axes)#das r hier markiert, dass jetz latex code kommt ax1.set_ylabel('Amount of cloud droplets', fontsize=size_axes) ax1.set_xlim(0,3.2) ax1.set_ylim([10**2,1*10**7]) #Hide the right and top spines ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) #Only show ticks on the left and bottom spines ax1.yaxis.set_ticks_position('left') ax1.xaxis.set_ticks_position('bottom') ax1.legend(loc=1, frameon=False, numpoints=1) #position of legend plt.show()
def get_plot(self, xlim=None, ylim=None): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """ import prettyplotlib as ppl from prettyplotlib import brewer2mpl ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allfrequencies = [] plt = get_publication_quality_plot(12, 8) # Note that this complicated processing of frequencies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): frequencies = dos['frequencies'] densities = dos['densities'] if y is None: y = np.zeros(frequencies.shape) if self.stack: y += densities newdens = y.copy() else: newdens = densities allfrequencies.append(frequencies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allfrequencies.reverse() allpts = [] for i, (key, frequencies, densities) in enumerate(zip(keys, allfrequencies, alldensities)): allpts.extend(list(zip(frequencies, densities))) if self.stack: plt.fill(frequencies, densities, color=colors[i % ncolors], label=str(key)) else: ppl.plot(frequencies, densities, color=colors[i % ncolors], label=str(key), linewidth=3) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Frequencies (THz)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt
import numpy as np import prettyplotlib as ppl import matplotlib.pyplot as plt import matplotlib as mpl from prettyplotlib import brewer2mpl font = {'size':12} mpl.rc('font', **font) bmap = brewer2mpl.get_map('Set2', 'qualitative', 6) colors = bmap.mpl_colors[::-1] mpl.rcParams['axes.color_cycle'] = colors data = np.load('../../data/F2_reorg_energy_data_vals_compiled_sorted.npz') reorg_energy_values = data['reorg_energy_values'] F2 = data['F2'] mean = data['mean'] data_K8 = np.load('../../remote_scripts/data/F2_reorg_energy_data_K8_vals_1-4.npz') F2_K8 = data_K8['F2_heom'] reorg_energy_K8 = data_K8['reorg_energy_values'] data_K9 = np.load('../../remote_scripts/data/F2_reorg_energy_data_K9_vals_1-4.npz') F2_K9 = data_K9['F2_heom'] reorg_energy_K9 = data_K9['reorg_energy_values'] pert_data = np.load('../../data/F2_reorg_energy_perturbative_data_large_reorg_energy.npz') pert_reorg_energy_values = pert_data['reorg_energy_values'] pert_F2 = pert_data['F2'] pert_mean = pert_data['mean']
import prettyplotlib as ppl from prettyplotlib import brewer2mpl import matplotlib.pyplot as plt import numpy as np #from analyzer import guard_percentages, sizes import matplotlib.ticker as ticker from matplotlib.colors import LogNorm import pandas as pd purples = brewer2mpl.get_map('Purples', 'Sequential', 9).mpl_colormap data = pd.read_csv('clean.txt', sep=' ', header=None) seq_times = np.array([43.05324205101351, 58.40454645099817, 72.48805438299314, 87.82189680699958, 105.97584470099537, 116.47462376701878, 144.88318312098272, 165.84237372799544, 176.9974813630106, 187.98173966401373, 203.43700645200443, 223.72902374199475]) print(data) print(data.head()) processes = [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 24, 28, 33, 40] raw = np.ones((12,19)) raw[:,:18] = data[2].reshape(12,18)
def extrapolation_sigma(all_interval1, all_data1_3, all_interval2, all_data2_3, all_interval3, all_data3_3, names1,names2,names3, p_title3, time_real_1,time_real_2,time_real_3, delta_s,t_real, dycoms, fitting, s_point): sp=5 #part of determination of first timestep of sigma calculation fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors #WE WILL ANALYZE THE DIFFERENT RE-NUMBER RUNS #DATA RE800 if (dycoms == 1): cf=5 else: cf=3 shape= np.shape(all_interval1) time_length=shape[1] data1_3= np.zeros(100) interval1= np.zeros(100) sigma_vector_1= np.zeros(time_length) for k in np.arange(sp+cf,time_length): data1_3[:] = all_data1_3[:,k] interval1[:] = all_interval1[:,k] log_data= np.zeros(100) for i in np.arange(len(data1_3)): if (data1_3[i] != 0): log_data[i] = np.log(data1_3[i]) elif (data1_3[i] == 0): log_data[i]=data1_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval1[s_point:end_pos+1], log_data[s_point:end_pos+1], 2) sigma_square=(1/(-2*z[0])) sigma_vector_1[k]= np.sqrt(sigma_square) sigma_fit_1 = np.polyfit(time_real_1[sp+cf:time_length], sigma_vector_1[sp+cf:time_length], 1) ax.plot(time_real_1[sp+cf:time_length],sigma_vector_1[sp+cf:time_length] , color=color_set[1],marker='.', linestyle='None',markersize=m_s , label=names1[3]) x_fit = np.linspace(0,60,1000) p = sigma_fit_1[0]*x_fit + sigma_fit_1[1] # if (dycoms != 0): # ax.plot(x_fit,p ,linestyle='--', color=color_set[2], label='Fiting', linewidth=l_w_1) #DATA RE400 cf=3 if (dycoms == 1): cf=5 shape= np.shape(all_interval2) time_length=shape[1] time_length_re400=shape[1] mean_fits400=np.zeros(50) data2_3= np.zeros(100) interval2= np.zeros(100) sigma_vector_2= np.zeros(time_length) for k in np.arange(sp+cf,time_length): data2_3[:] = all_data2_3[:,k] interval2[:] = all_interval2[:,k] log_data= np.zeros(100) for i in np.arange(len(data2_3)): if (data2_3[i] != 0): log_data[i] = np.log(data2_3[i]) elif (data2_3[i] == 0): log_data[i]=data2_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break mean_fits400[k]=log_data[s_point] z = np.polyfit(interval2[s_point:end_pos+1], log_data[s_point:end_pos+1], 2) sigma_square=(1/(-2*z[0])) sigma_vector_2[k]= np.sqrt(sigma_square) #print sigma_square, z[0] sigma_fit_2 = np.polyfit(time_real_2[sp+cf:time_length], sigma_vector_2[sp+cf:time_length], 1) ax.plot(time_real_2[sp+cf:time_length],sigma_vector_2[sp+cf:time_length] , color=color_set[3],marker='.',linestyle='None',markersize=m_s, label=names2[3]) if (dycoms != 0): #LIQUID AFTER SPECIFIED TIME #1 hour x_fit = np.linspace(0,60,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=60: ', p[len(p)-1] #2 hour x_fit = np.linspace(0,120,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=120: ', p[len(p)-1] #6 hour x_fit = np.linspace(0,360,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=360: ', p[len(p)-1] #12 hour x_fit = np.linspace(0,720,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=720: ', p[len(p)-1] #24 hour x_fit = np.linspace(0,1440,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=1440: ', p[len(p)-1] #48 hour x_fit = np.linspace(0,2880,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=2880: ', p[len(p)-1] x_fit = np.linspace(0,40,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'Verschiebung: ', sigma_fit_2[1], 'Steigung: ', sigma_fit_2[0] if (dycoms != 0): if (fitting == 1): print 'sigma at x=40: ', p[len(p)-1] ax.plot(x_fit,p ,linestyle='--', color=color_set[3], label='Fitting', linewidth=l_w_2) if (dycoms == 0): #DATA RE200 cf=0 shape= np.shape(all_interval3) time_length=shape[1] data3_3= np.zeros(100) interval3= np.zeros(100) sigma_vector= np.zeros(time_length) #print sigma_vector[9] c= np.zeros(time_length) mean_fits200=np.zeros(50) for k in np.arange(sp+cf,time_length): data3_3[:] = all_data3_3[:,k] interval3[:] = all_interval3[:,k] log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data3_3)): if (data3_3[i] != 0): log_data[i] = np.log(data3_3[i]) elif (data3_3[i] == 0): log_data[i]=data3_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break mean_fits200[k]=log_data[s_point] z = np.polyfit(interval3[s_point:end_pos+1], log_data[s_point:end_pos+1], 2) sigma_square=(1/(-2*z[0])) sigma_vector[k]= np.sqrt(sigma_square) sigma_fit = np.polyfit(time_real_3[sp+cf:time_length], sigma_vector[sp+cf:time_length], 1) #print 'sigma_fit', sigma_fit #LIQUID AFTER SPECIFIED TIME #30 min x_fit = np.linspace(0,30,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=30: ', p[len(p)-1] #40 min x_fit = np.linspace(0,40,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=40: ', p[len(p)-1] #40 min x_fit = np.linspace(0,41,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=41: ', p[len(p)-1] #50 min x_fit = np.linspace(0,50,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=50: ', p[len(p)-1] #1 hour x_fit = np.linspace(0,60,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=60: ', p[len(p)-1] #2 hour x_fit = np.linspace(0,120,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=120: ', p[len(p)-1] #6 hour x_fit = np.linspace(0,360,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=360: ', p[len(p)-1] #12 hour x_fit = np.linspace(0,720,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=720: ', p[len(p)-1] #24 hour x_fit = np.linspace(0,1440,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=1440: ', p[len(p)-1] #48 hour x_fit = np.linspace(0,2880,10000) p = sigma_fit_2[0]*x_fit + sigma_fit_2[1] print 'sigma at x=2880: ', p[len(p)-1] x_fit = np.linspace(0,40,10000) p = sigma_fit[0]*x_fit + sigma_fit[1] print 'Verschiebung: ', sigma_fit[1], 'Steigung: ', sigma_fit[0] ax.plot(time_real_3[sp+cf:time_length],sigma_vector[sp+cf:time_length] , color=color_set[5],marker='.',linestyle='None',markersize=m_s, label=names3[3]) if (fitting == 1): print 'sigma at x=40: ', p[len(p)-1] ax.plot(x_fit,p , color=color_set[5],linestyle='--', linewidth=l_w_2, label='Fitting') #GENERAL PLOT SETTINGS # if(dycoms == 0): # plt.title(r'VERDI - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font) # else: # plt.title(r'DYCOMS-II - Growth of $\sigma$ in time', fontsize=size_title)#,fontdict=font) plt.xlabel('t [min]')#, fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel(r'\textbf{$\sigma$}', fontsize=90)#, fontsize=size_axes)#,fontdict=font) #plt.xlim(0,40) if (fitting == 1): plt.ylim(0,0.35) plt.xlim(0,25) else: plt.ylim(0,0.35) plt.xlim(2,22) plt.legend(loc=2, frameon=False) plt.show() plt.clf() fig, ax = ppl.subplots() if(dycoms == 0): print 'after plot', time_real_3 , sp+cf, time_length print 'first time step', time_real_3[sp+cf] print mean_fits200 print 'first', mean_fits200[sp+cf], 'at point', sp+cf if(dycoms == 0): ax.plot(time_real_3[sp+cf:time_length],(mean_fits200[sp+cf:time_length]/mean_fits200[sp+cf]), color=color_set[5],linestyle='--',linewidth=l_w_2, label='Droplet number') else: ax.plot(time_real_2[sp+cf:time_length_re400],(mean_fits400[sp+cf:time_length_re400]/mean_fits400[sp+cf]), color=color_set[5],linestyle='--',linewidth=l_w_2, label='Droplet number') plt.xlabel('t [min]')#, fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel(r'$N_{1.35}(t) / N_{1.35}(t_{0})$')#, fontsize=size_axes)#,fontdict=font) #ax.set_yscale('symlog') #plt.ylim(0.98,1.02) #plt.legend(loc=1, frameon=False) plt.show()
def get_plot(self, xlim=None, ylim=None, plt=None, handle_only=False): """ Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. plt: Handle on existing plot. handle_only: Quickly return just a handle. Useful if this method raises an exception so that one can close() the figure. """ plt = plt or pretty_plot(2, 5.5) if handle_only: return plt ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allenergies = [] width = 4 ticksize = int(width * 2.5) axes = plt.gca() axes.set_title(axes.get_title(), size=width * 4) labelsize = int(width * 3) axes.set_xlabel(axes.get_xlabel(), size=labelsize) axes.set_ylabel(axes.get_ylabel(), size=labelsize) axes.xaxis.labelpad = 6 # Note that this complicated processing of energies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): energies = dos['energies'] densities = dos['densities'] if not y: y = {Spin.up: np.zeros(energies.shape), Spin.down: np.zeros(energies.shape)} newdens = {} for spin in [Spin.up, Spin.down]: if spin in densities: if self.stack: y[spin] += densities[spin] newdens[spin] = y[spin].copy() else: newdens[spin] = densities[spin] allenergies.append(energies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allenergies.reverse() allpts = [] for i, key in enumerate(keys): x = [] y = [] for spin in [Spin.up, Spin.down]: if spin in alldensities[i]: densities = list(int(spin) * alldensities[i][spin]) energies = list(allenergies[i]) if spin == Spin.down: energies.reverse() densities.reverse() y.extend(energies) x.extend(densities) allpts.extend(list(zip(x, y))) if self.stack: plt.fill(x, y, color=colors[i % ncolors], label=str(key)) else: ppl.plot(x, y, color=colors[i % ncolors], label=str(key), linewidth=1) if not self.zero_at_efermi: xlim = plt.xlim() ppl.plot(xlim, [self._doses[key]['efermi'], self._doses[key]['efermi']], color=colors[i % ncolors], linestyle='--', linewidth=1) if ylim: plt.ylim(ylim) if xlim: plt.xlim(xlim) else: ylim = plt.ylim() relevantx = [p[0] for p in allpts if ylim[0] < p[1] < ylim[1]] plt.xlim(min(relevantx), max(relevantx)) if self.zero_at_efermi: xlim = plt.xlim() plt.plot(xlim, [0, 0], 'k--', linewidth=1) plt.ylabel(r'$\mathrm{E\ -\ E_f\ (eV)}$') plt.xlabel(r'$\mathrm{Density\ of\ states}$') locs, _ = plt.xticks() plt.xticks([0], fontsize=ticksize) plt.yticks(fontsize=ticksize) plt.grid(which='major', axis='y') plt.legend(fontsize='x-small', loc='upper right', bbox_to_anchor=(1.15, 1)) leg = plt.gca().get_legend() leg.get_frame().set_alpha(0.25) plt.tight_layout() return plt
def plot_fitting(interval3, data3_1, data3_2, data3_3): #COLORS FOR FIGURES fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors #SCALE DATA data3_3=data3_3*50/18*0.92 #ax.plot(interval3,data3_3,color=color_set_2[8],linewidth=l_w_1, label=names3[3]) #!!!!!!!!!!!!! #Fitting #!!!!!!!!!!!!! log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data3_3)): if (data3_3[i] != 0): log_data[i] = np.log(data3_3[i]) elif (data3_3[i] == 0): log_data[i]=data3_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break begin_pos=s_point print 'mean is set to', interval3[begin_pos] z = np.polyfit(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], 2) print 'polyfit',z p = np.poly1d(z) ax.plot(interval3[begin_pos:end_pos+1], log_data[begin_pos:end_pos+1], marker='D', color=color_set[5], label='Fitting points' ) ax.plot(interval3, log_data, '-', color=color_set_2[8],linewidth=l_w_1, label='Lagrange' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) #!!!!!!!! #VERDI CAREFULL OLD VALUE FOR SIGAM EXTRAPOLATION #!!!!!!!! sigma_extrapolation=0.8**2 a=-1/(2*sigma_extrapolation) mean_extrapolation=z[1]/(-2*a) x = np.linspace(0,mean+6,1000) print 'mean and sigma_square', mean, sigma_square y_log=( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) ax.plot(x,y_log , color=color_set[2], label='Gaussian fit', linestyle='--', linewidth=l_w_2) #PLOT PROPERTIES plt.xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font) plt.legend(loc=1, frameon=False) plt.xlim(0,4) plt.ylim(0,20) plt.show()
with open("figure_5_3.pik","w") as fi: print "Writing pickle to figure_5_3.pik" pic.dump({'alphas':alphas,'phis':phis,'mean_field':eps,'stochastic':stoc_eps},fi) print "Plotting..." font = {'size':12} plt.rc('font',**font) fig, (ax1,ax2) = ppl.subplots(1,2,figsize = (12,5)) alphas2,phis2 = np.meshgrid(np.arange(alphas.min(),alphas.max()+dalpha,dalpha)-dalpha/2, np.arange(phis.min(),phis.max()+dphi,dphi)-dphi/2) yellorred = brewer2mpl.get_map('YlOrRd','Sequential',9).mpl_colormap p = ax1.pcolormesh(alphas2,phis2,eps.T,cmap=yellorred, rasterized=True) ax1.axis([alphas2.min(),alphas2.max(),phis2.min(),phis2.max()]) #xticks = np.arange(alphas.min(),alphas.max(),0.5) #xlabels = np.arange(alphas.min(),alphas.max(),0.5)-alphas.min() #yticks = np.arange(phis.min(),phis.max(),0.5) #ylabels = np.arange(phis.min(),phis.max(),0.5)-phis.min() #plt.xticks(xticks,xlabels,axes=ax1) #plt.yticks(yticks,ylabels,axes=ax1) cb = plt.colorbar(p, ax=ax1) cb.set_ticks(np.array([0.3,0.4,0.5]))
def several_times(all_interval3, all_data3_3, names3, p_title3, time_real_1,time_real_2,time_real_3, delta_s,t_real, time_data, dycoms, fitting, s_point): #COLORS FOR FIGURES fig, ax = plt.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors #color_set_2 = brewer2mpl.get_map('Reds', 'sequential', 9).mpl_colors color_set_3 = brewer2mpl.get_map('Dark2', 'qualitative', 8).mpl_colors #SCALE DATA if (dycoms == 0): all_data3_3=all_data3_3*50/18*0.92 else: all_data3_3=all_data3_3*30/18*1.75 shape= np.shape(all_interval3) time_length=shape[1] print time_length #EXPLICIT PLOT OF DIFFERENT TIME STEPS k=0 #VERDI # k=10 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x=str(time_buffer)+ ' min' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[0],linewidth=l_w_1, label=name_x) k=3 #VERDI # k=10 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x=str(time_buffer)+ ' min' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[1],linewidth=l_w_1, label=name_x) k=8 #VERDI # k=14 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x=str(time_buffer)+ ' min' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[3],linewidth=l_w_1, label=name_x) k=13 #VERDI # k=20 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x=str(time_buffer)+ ' min' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[5],linewidth=l_w_1, label=name_x) # k=22 #VERDI k=22 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x=str(time_buffer)+ ' min' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[7],linewidth=l_w_1, label=name_x) # k=35 #VERDI k=35 time_buffer=round(time_data[k]*t_real/60,2) print 'real time t3',time_buffer name_x=str(time_buffer)+ ' min' ax.plot(all_interval3[:,k],all_data3_3[:,k],color=color_set[9],linewidth=l_w_1, label=name_x) #PLOT PROPERTIES ax.set_yscale('symlog') ax.set_xlabel(r'$M/M_r$', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt ax.set_ylabel('Amount of cloud droplets', fontsize=size_axes)#,fontdict=font) ax.set_xticks([0.1,0.5,1,1.5,2.0,2.5,3.0,3.5,4.0]) ax.set_xlim(0.1,3) ax.set_ylim([10,10**8]) ax2 = ax.twiny() ax2.set_xlabel(r"Radius [$\mu m$]", fontsize=size_axes) if (dycoms==0): tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0] tick_lbls = [8.2,10.3,11.8,13,14,14.9,15.7,16.4] else: tick_locs = [0.5,1,1.5,2.0,2.5,3.0,3.5,4.0] tick_lbls = [8.9,11,12.8,14,15.2,16.1,17,17.7] ax2.set_xticks(tick_locs) ax2.set_xticklabels(tick_lbls) ax2.set_xlim(0.1,3) ax.legend(loc=0, frameon=False) plt.legend(loc=1, frameon=False) plt.show()
import matplotlib.pyplot as plt from prettyplotlib import brewer2mpl from matplotlib.colors import LogNorm import numpy as np from matplotlib import cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap import sys sys.path.append('out') from generated_grid import * # --- COLORS --- green_purple = brewer2mpl.get_map('PRGn', 'diverging', 11).mpl_colormap red_purple = brewer2mpl.get_map('RdPu', 'Sequential', 9).mpl_colormap greys = brewer2mpl.get_map('greys', 'Sequential', 9).mpl_colormap def make_map(r, g, b): N = 256 vals = np.ones((N, 4)) vals[:, 0] = np.linspace(1, r / 256, N) vals[:, 1] = np.linspace(1, g / 256, N) vals[:, 2] = np.linspace(1, b / 256, N) return ListedColormap(vals) #sparql_colors = make_map( 11, 69, 157) #cypher_colors = make_map( 0, 138, 188)
def plot_data_compare_2(interval1,data1_1, data1_2, data1_3, interval2, data2_1, data2_2, data2_3, interval3, data3_1, data3_2, data3_3, interval_flight, data_flight, names1, style, p_title1, names2, p_title2, names3, p_title3,dycoms): close='all' if ( style == 0): fig, ax = ppl.subplots() color_set = brewer2mpl.get_map('paired', 'qualitative', 12).mpl_colors color_set_2 = brewer2mpl.get_map('PuBu', 'sequential', 9).mpl_colors # ax.plot(interval1,data1_1, color='black', label=names1[1]) # ax.plot(interval1,data1_2, color='red', label=names1[2]) # ax.plot(interval1,data1_3, color='blue',linestyle='-', label=names1[3]) ax.plot(interval1,data1_3, color=color_set_2[4],linewidth=2, label=names1[3]) data2_1=data2_1*30/18 # add the scaling factor data2_2=data2_2*30/18 if (dycoms ==0): data2_3=data2_3*30/18*1.9 else: data2_3=data2_3*30/18*2 # ax.plot(interval2,data2_1, color='black',linestyle='--', label=names2[1]) # ax.plot(interval2,data2_2, color='red',linestyle='--', label=names2[2]) ax.plot(interval2,data2_3, color=color_set_2[6],linewidth=2, label=names2[3]) if (dycoms==0): data3_1=data3_1*50/18 # add the scaling factor data3_2=data3_2*50/18 data3_3=data3_3*50/18*0.92 # ax.plot(interval3,data3_1, color='black',linestyle=':',linewidth=2, label=names3[1]) # ax.plot(interval3,data3_2, color='red',linestyle=':',linewidth=2, label=names3[2]) ax.plot(interval3,data3_3,color=color_set_2[8],linewidth=2, label=names3[3]) ######################################################################## #playground ######################################################################## # print interval1[0:34] # print data1_3[0:34] # size=1000000 # dist_names = ['alpha', 'beta', 'arcsine', # 'weibull_min', 'weibull_max', 'rayleigh'] # # for dist_name in dist_names: # dist = getattr(scipy.stats, dist_name) # param = dist.fit(data1_3[23:34]) # pdf_fitted = dist.pdf(interval1[23:34], *param[:-2], loc=param[-2], scale=param[-1]) * size # ax.plot(pdf_fitted, label=dist_name) # plt.legend(loc='upper left') # beg=26 # end=beg+34 # beg_l=beg+1 # end_l=beg_l+15 # mirror=np.zeros(50) # dummy=np.zeros(16) # dummy[0:15]=data3_3[beg_l:end_l] # dummy=dummy[::-1] # mirror[0:16]=dummy[0:16] # mirror[16:50]=data3_3[beg:end] # integral_data= np.zeros(1) # for i in np.arange(23,len(data3_3)): # integral_data=integral_data+data3_3[i]*0.05 # approx_var_1= np.zeros(1) # approx_var_2= np.zeros(1) # j=0 # for i in np.arange(21,len(data3_3)): # if (approx_var_2 < 1 ): # approx_var_1=approx_var_1+ data3_3[i]*0.05 # #approx_var_2=approx_var_1 -integral_data*2*0.3413 # approx_var_2=approx_var_1 -np.std(mirror) # j=j+1 if (dycoms ==0): log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data3_3)): if (data3_3[i] != 0): log_data[i] = np.log(data3_3[i]) elif (data3_3[i] == 0): log_data[i]=data3_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval3[24:end_pos+1], log_data[24:end_pos+1], 2) print 'polyfit',z p = np.poly1d(z) #ax.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) sigma_extrapolation=0.8**2 a=-1/(2*sigma_extrapolation) mean_extrapolation=z[1]/(-2*a) x = np.linspace(0,mean+6,1000) print 'mean and sigma_square', mean, sigma_square #y= (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) #STATISTICS skewness=0 for o in np.arange(len(x)): skewness=skewness +((x[0]-mean)/np.sqrt(sigma_square))**3 skewness=skewness/len(x) print 'skewness', skewness ax.plot(x,y , color=color_set[2], label='Gaussian fit', linestyle='--', linewidth=2) ax.plot(x,y_extrapolation , color=color_set[5], label='Gaussian extrapolation t=60', linestyle='--', linewidth=2) data_flight=data_flight *5*10**7 ax.plot(interval_flight,data_flight, color=color_set[9],linestyle='-', linewidth=3, label='Flight measurements') else: log_data= np.zeros(100) log_interval= np.zeros(100) for i in np.arange(len(data2_3)): if (data2_3[i] != 0): log_data[i] = np.log(data2_3[i]) elif (data2_3[i] == 0): log_data[i]=data2_3[i] j=1 max_val=max(log_data) max_val_pos=len(log_data)+1 for i in np.arange(len(log_data)): if ( log_data[i] == max_val): max_val_pos=i if (i > max_val_pos): if (log_data[i] <= 0): end_pos=i break z = np.polyfit(interval2[24:end_pos+1], log_data[24:end_pos+1], 2) print 'polyfit',z p = np.poly1d(z) #ax.plot(interval3[24:end_pos+1], np.exp(log_data[24:end_pos+1]), '.', color=color_set[4], label='Fiting points' ) mean=z[1]/(-2*z[0]) sigma_square=(1/(-2*z[0])) sigma_extrapolation=0.8**2 a=-1/(2*sigma_extrapolation) mean_extrapolation=z[1]/(-2*a) x = np.linspace(0,mean+6,1000) print 'mean and sigma_square', mean, sigma_square #y= (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) y=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_square)) ) y_extrapolation=np.exp( (z[2]+z[1]**2/(4*-z[0]))-(((x-mean)**2)/(2*sigma_extrapolation)) ) ax.plot(x,y , color=color_set[3], label='Gaussian fit', linestyle='--', linewidth=2) # ax.plot(x,y_extrapolation , color=color_set[5], label='Gaussian extrapolation t=60', linestyle='--', linewidth=2) # ax.plot(interval1[beg-16:beg+34],mirror, color='red') # mean = 1.24 # variance = 0.009 # variance_arb = 0.001 # sigma = np.sqrt(variance) # x = np.linspace(-3,5,1000) # y = mlab.normpdf(x,mean,sigma) # y = y*20000*(variance_arb/variance) # ax.plot(x,y, color='magenta') ######################################################################## #playground end ######################################################################## #axes = plt.gca() #axes.grid(True) ax.set_yscale('symlog') #ax.set_title(p_title3)#,fontdict=font) # if (dycoms ==0): # plt.title(p_title3, fontsize=size_title)#,fontdict=font) # else: # plt.title(p_title2, fontsize=size_title)#,fontdict=font) plt.xlabel('Liquid', fontsize=size_axes)#,fontdict=font) #das r hier markiert, dass jetz latex code kommt plt.ylabel('Amount of particles', fontsize=size_axes)#,fontdict=font) plt.xlim(0,4) plt.ylim([10,10**8]) plt.legend(loc=1, frameon=False) plt.show()