def comentionfigure(request): term_count = {} for i in Article_content.objects.all(): words = Article_content.key_word(i) for word in words: if word not in term_count: term_count[word] = 1 else: term_count[word] = term_count[word] + 1 data = pd.DataFrame.from_dict(term_count, orient='index') data = data.reset_index() data.columns = ['Terms', 'Count'] terms = data.sort_values(by=['Count'], ascending=False).head(20) terms = terms[2:] terms1 = terms.sort_index() qs = Article_content.objects.all() df = read_frame(qs) text = " ".join(content for content in df.content) stopwords1 = set(STOPWORDS) qs1 = Article.objects.all() df1 = read_frame(qs1) df1['date'] = df1['date_of_publish'].apply( lambda x: pd.to_datetime(str(x), format='%Y-%m-%d')) df1['YM'] = df1['date'].apply(lambda x: str(x.year) + '-' + str(x.month)) c = list() for d in df1.YM.unique(): count = len(df1[df1.YM == d]) c.append(count) result = pd.DataFrame(list(zip(df1.YM.unique(), c)), columns=['Publish_Time', 'Num']) result['date'] = result['Publish_Time'].apply( lambda x: pd.to_datetime(str(x), format='%Y-%m')) result = result.sort_values(by='date') ind = np.arange(len(df1.YM.unique())) # Generate a word cloud image wordcloud = WordCloud(stopwords=stopwords1, background_color="white", colormap='viridis').generate(text) font = FontProperties() font.set_family('serif') font.set_name('Arial Rounded MT') font.set_style('italic') plt.figure(figsize=(100, 120), facecolor='white') fig, ax = plt.subplots(2, 1) ax[1].imshow(wordcloud, interpolation='bilinear') ax[1].axis('off') ax[0].plot(ind, result.Num) ax[0].set_xticks([1, 5, 10]) ticks = list(result.Publish_Time) t = (ticks[1], ticks[5], ticks[10]) ax[0].set_xticklabels(t) buf = io.BytesIO() canvas = FigureCanvasAgg(fig) canvas.print_png(buf) response = HttpResponse(buf.getvalue(), content_type='image/png') # if required clear the figure for reuse fig.clear() # I recommend to add Content-Length for Django response['Content-Length'] = str(len(response.content)) return response
def __create_surface(self, dimension): """! @brief Prepares surface for showing network structure in line with specified dimension. @param[in] dimension (uint): Dimension of processed data (external stimulus). @return (tuple) Description of surface for drawing network structure. """ rcParams['font.sans-serif'] = ['Arial'] rcParams['font.size'] = 12 fig = plt.figure() axes = None if (dimension == 2): axes = fig.add_subplot(111) elif (dimension == 3): axes = fig.gca(projection='3d') surface_font = FontProperties() surface_font.set_name('Arial') surface_font.set_size('12') return (fig, axes)
def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''): '''format 2d-plot black and with with times legends ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() font.set_name('Script MT') font.set_family('serif') font.set_style('normal') # font.set_size('small') font.set_size('large') font.set_variant('normal') font.set_weight('medium') if xlim != None and ylim != None: axes.axis([0, xlim, 0., ylim], fontproperties=font) # format ticks for plot # locs, labels = axes.xticks() axes.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) axes.xlabel(xlabel, fontproperties=font) locs, labels = axes.yticks() axes.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) axes.ylabel(ylabel, fontproperties=font)
def show_network(self): """! @brief Shows connections in the network. It supports only 2-d and 3-d representation. """ if (self.__ccore_network_pointer is not None): raise NameError("Not supported for CCORE"); dimension = len(self._osc_loc[0]); if ( (dimension != 3) and (dimension != 2) ): raise NameError('Network that is located in different from 2-d and 3-d dimensions can not be represented'); from matplotlib.font_manager import FontProperties; from matplotlib import rcParams; rcParams['font.sans-serif'] = ['Arial']; rcParams['font.size'] = 12; fig = plt.figure(); axes = None; if (dimension == 2): axes = fig.add_subplot(111); elif (dimension == 3): axes = fig.gca(projection='3d'); surface_font = FontProperties(); surface_font.set_name('Arial'); surface_font.set_size('12'); for i in range(0, self._num_osc, 1): if (dimension == 2): axes.plot(self._osc_loc[i][0], self._osc_loc[i][1], 'bo'); if (self._conn_represent == conn_represent.MATRIX): for j in range(i, self._num_osc, 1): # draw connection between two points only one time if (self.has_connection(i, j) == True): axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], 'b-', linewidth = 0.5); else: for j in self.get_neighbors(i): if ( (self.has_connection(i, j) == True) and (i > j) ): # draw connection between two points only one time axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], 'b-', linewidth = 0.5); elif (dimension == 3): axes.scatter(self._osc_loc[i][0], self._osc_loc[i][1], self._osc_loc[i][2], c = 'b', marker = 'o'); if (self._conn_represent == conn_represent.MATRIX): for j in range(i, self._num_osc, 1): # draw connection between two points only one time if (self.has_connection(i, j) == True): axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], [self._osc_loc[i][2], self._osc_loc[j][2]], 'b-', linewidth = 0.5); else: for j in self.get_neighbors(i): if ( (self.has_connection(i, j) == True) and (i > j) ): # draw connection between two points only one time axes.plot([self._osc_loc[i][0], self._osc_loc[j][0]], [self._osc_loc[i][1], self._osc_loc[j][1]], [self._osc_loc[i][2], self._osc_loc[j][2]], 'b-', linewidth = 0.5); plt.grid(); plt.show();
def main(argv): parser = argparse.ArgumentParser( description='Analyse the distribution of MMPBSA/MMGBSA delta G') parser.add_argument( 'infile', help='input file containing energy totals (CSV format)') parser.add_argument('sumfile', help='summary file (text format)') parser.add_argument( 'trendfile', help='trend plot with confidence intervals (.png, .bmp, .pdf)') parser.add_argument( 'distfile', help='distribution plot of energy totals (.png, .bmp, .pdf)') args = parser.parse_args() global mean_results font = FontProperties() font.set_name('Calibri') font.set_size(28) means = read_csv(args.infile) results_m = [] results_u = [] results_l = [] xs = [] with open(args.sumfile, 'w') as fo: for i in range(5, len(means) + 5, 5): mean_results = [] bounds = conf_intervals(means["TOTAL"][:i]) fo.write("%d mean %0.2f +%0.2f -%0.2f\n" % (i, bounds[0], bounds[1], bounds[2])) results_m.append(bounds[0]) results_u.append(bounds[1] + bounds[0]) results_l.append(bounds[2] + bounds[0]) xs.append(i) plt.plot(xs, results_m, color='g') plt.plot(xs, results_u, linestyle='--', color='g') plt.plot(xs, results_l, linestyle='--', color='g') plt.locator_params(nbins=5, axis='y') plt.xlabel(u'Samples', fontproperties=font) plt.ylabel(u'\u0394G (kcal/mol)', fontproperties=font) plt.tight_layout() plt.savefig(args.trendfile) pdmeans = Series(mean_results) lim_l = round(bounds[0] - 2.5, 0) plt.xlim(lim_l, lim_l + 5) plt.ylim(0, 900) plt.locator_params(nbins=5, axis='y') plt.xlabel(u'Bootstrapped mean \u0394G (kcal/mol)', fontproperties=font) plt.ylabel(u'Frequency', fontproperties=font) plt.hist(pdmeans, bins=50) plt.savefig(args.distfile)
def set_ax_param(ax, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True, grid=True): """! @brief Sets parameters for matplotlib ax. @param[in] ax (Axes): Axes for which parameters should applied. @param[in] x_title (string): Title for Y. @param[in] y_title (string): Title for X. @param[in] x_lim (double): X limit. @param[in] y_lim (double): Y limit. @param[in] x_labels (bool): If True - shows X labels. @param[in] y_labels (bool): If True - shows Y labels. @param[in] grid (bool): If True - shows grid. """ from matplotlib.font_manager import FontProperties from matplotlib import rcParams if (_platform == "linux") or (_platform == "linux2"): rcParams['font.sans-serif'] = ['Liberation Serif'] else: rcParams['font.sans-serif'] = ['Arial'] rcParams['font.size'] = 12 surface_font = FontProperties() if (_platform == "linux") or (_platform == "linux2"): surface_font.set_name('Liberation Serif') else: surface_font.set_name('Arial') surface_font.set_size('12') if (y_title is not None): ax.set_ylabel(y_title, fontproperties=surface_font) if (x_title is not None): ax.set_xlabel(x_title, fontproperties=surface_font) if (x_lim is not None): ax.set_xlim(x_lim[0], x_lim[1]) if (y_lim is not None): ax.set_ylim(y_lim[0], y_lim[1]) if (x_labels is False): ax.xaxis.set_ticklabels([]) if (y_labels is False): ax.yaxis.set_ticklabels([]) ax.grid(grid)
def gcm_heatmaps(gcms, ginfo, out_file, title_tag, colormap='RdYlBu_r'): with PdfPages(out_file) as pdf: font0 = FontProperties() font0.set_name('sans-serif') font0.set_size(12) font1 = font0.copy() font1.set_size(14) font2 = font0.copy() font2.set_size(16) for i, GCM in enumerate(gcms): title = "%s (|cor|> %.3f, %d nodes, %d edges)" % \ (title_tag, ginfo.loc[i, 'AbsCor'], ginfo.loc[i, 'NumNodes'], ginfo.loc[i, 'NumEdges']) fig = plt.figure(1, figsize=(8, 8)) ax = fig.add_subplot(111) im = ax.matshow(GCM, aspect='equal', cmap=matplotlib.cm.get_cmap(colormap), vmin=-1.0, vmax=1.0) ax.set_title(title, fontproperties=font2) labels = list(map(str, GCM_ORDER)) xticks = np.arange(len(labels)) yticks = np.arange(len(labels)) ax.set_xticks(xticks) ax.set_yticks(yticks) ax.set_xticklabels(labels, fontproperties=font1) ax.set_yticklabels(labels, fontproperties=font1) plt.setp(list(ax.spines.values()), lw=0.5, color="#666666") plt.setp(ax.get_xticklabels(), fontproperties=font1) plt.setp(ax.get_yticklabels(), fontproperties=font1) plt.setp(ax.xaxis.get_ticklines(), markersize=3) plt.setp(ax.yaxis.get_ticklines(), markersize=3) plt.setp(ax.xaxis.get_ticklines(minor=True), markersize=1) plt.setp(ax.yaxis.get_ticklines(minor=True), markersize=1) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('right') pdf.savefig() plt.close()
def plot(self, n_bins=100): """ Plots MCMC posterior data. """ from matplotlib.font_manager import FontProperties import matplotlib.pyplot as plt font = FontProperties() font.set_name('serif') plt.style.use('classic') # plot chains versus iterations. plt.figure(1) for num, parameter in zip(range(self.n_params), self.parameters): plt.subplot(self.n_params, 1, num + 1) plt.plot(self.posteriors[parameter], 'b-') plt.figure(2) from matplotlib.gridspec import GridSpec gs = GridSpec(self.n_params, self.n_params) count = 0 for num1, parameter1 in zip(range(self.n_params), self.parameters): for num2, parameter2 in zip(range(self.n_params), self.parameters): if (num1 == num2): plt.subplot(gs[num1, num2]) plt.hist(self.posteriors[parameter1], bins=n_bins, histtype='step') plt.xticks([]) plt.yticks([]) elif (num1 > num2): plt.subplot(gs[num1, num2]) hist2D, xedges, yedges = np.histogram2d(self.posteriors[parameter2], self.posteriors[parameter1], bins=50) dx = xedges[1] - xedges[0] dy = yedges[1] - yedges[0] x = np.linspace(xedges[0] + dx, xedges[len(xedges)-2] + dx, num=len(xedges)-1) y = np.linspace(yedges[0] + dy, yedges[len(yedges)-2] + dy, num=len(yedges)-1) plt.pcolormesh(x, y, hist2D, cmap='Blues') else: pass count += 1 plt.show()
def set_ax_param(ax, x_title = None, y_title = None, x_lim = None, y_lim = None, x_labels = True, y_labels = True, grid = True): """! @brief Sets parameters for matplotlib ax. @param[in] ax (Axes): Axes for which parameters should applied. @param[in] x_title (string): Title for Y. @param[in] y_title (string): Title for X. @param[in] x_lim (double): X limit. @param[in] y_lim (double): Y limit. @param[in] x_labels (bool): If True - shows X labels. @param[in] y_labels (bool): If True - shows Y labels. @param[in] grid (bool): If True - shows grid. """ from matplotlib.font_manager import FontProperties; from matplotlib import rcParams; if (_platform == "linux") or (_platform == "linux2"): rcParams['font.sans-serif'] = ['Liberation Serif']; else: rcParams['font.sans-serif'] = ['Arial']; rcParams['font.size'] = 12; surface_font = FontProperties(); if (_platform == "linux") or (_platform == "linux2"): surface_font.set_name('Liberation Serif'); else: surface_font.set_name('Arial'); surface_font.set_size('12'); if (y_title is not None): ax.set_ylabel(y_title, fontproperties = surface_font); if (x_title is not None): ax.set_xlabel(x_title, fontproperties = surface_font); if (x_lim is not None): ax.set_xlim(x_lim[0], x_lim[1]); if (y_lim is not None): ax.set_ylim(y_lim[0], y_lim[1]); if (x_labels is False): ax.xaxis.set_ticklabels([]); if (y_labels is False): ax.yaxis.set_ticklabels([]); ax.grid(grid);
def visualize(dictionaryList): allRates = [] for dic in dictionaryList: allRates.append(dic['syllRate']) allRates = numpy.sort(numpy.array(allRates)) median = numpy.median(allRates) median_absolute_deviation = round(robust.mad(allRates), 2) lowerLimit = (median - (LimitDeviations * median_absolute_deviation)) upperLimit = (median + (LimitDeviations * median_absolute_deviation)) fig, ax = plt.subplots() ax.set_xlabel("Syllable rate per turn (syllables / second)") ax.set_ylabel("Number of turns") ax.hist(allRates, bins=20, color='c', edgecolor='k') ax.axvline(median, color='k', linestyle='dashed', linewidth=1, label="Median") ax.axvline(lowerLimit, color='r', linestyle='dashed', linewidth=1, label="Median + 2 * MAD") ax.axvline(upperLimit, color='r', linestyle='dashed', linewidth=1, label="Median - 2 * MAD") ax.set_xlim((0, 10)) font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') fig.figsize = (10, 4) fig.legend(fancybox=True, framealpha=0.5, frameon=True, loc='upper right') leg = fig.legend() leg.get_frame().set_edgecolor('b') fig.show()
def plot_confusion_matrix(cm, class_names, model): """ Returns a matplotlib figure containing the plotted confusion matrix. Args: cm (array, shape = [n, n]): a confusion matrix of integer classes class_names (array, shape = [n]): String names of the integer classes credit: https://towardsdatascience.com/exploring-confusion-matrix-evolution-on-tensorboard-e66b39f4ac12 """ cm = cm.cpu().detach().numpy() font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_style('normal') figure = plt.figure(figsize=(8, 8)) plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) plt.title("Confusion matrix") plt.colorbar() tick_marks = np.arange(len(class_names)) plt.xticks(tick_marks, class_names, rotation=45) plt.yticks(tick_marks, class_names) # Normalize the confusion matrix. cm = np.around(cm.astype('float') / cm.sum(axis=1)[:, np.newaxis], decimals=2) # Use white text if squares are dark; otherwise black. threshold = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): color = "white" if cm[i, j] > threshold else "black" plt.text(j, i, cm[i, j], horizontalalignment="center", color=color) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') figure.savefig(f'experiments/{model}/test_mtx.png')
def fineplot(start, stop, y, title, lx, ly, lg): pts = len(y) x = np.linspace(start, stop, pts) font = FontProperties() font.set_family('serif') font.set_name('Arial') # font.set_style('italic') fig, ax = plt.subplots() ax.plot(x, y, 'k', linewidth=1, label=lg) ax.legend(prop=font) ax.set_xlabel(lx, fontname="Arial", fontsize=14) ax.set_ylabel(ly, fontname="Arial", fontsize=14) ax.set_title(title, fontname='Arial', fontsize=18) for tick in ax.get_xticklabels(): tick.set_fontname("Arial") for tick in ax.get_yticklabels(): tick.set_fontname("Arial") plt.show() exit()
font_label.set_weight('bold') font_tick = font0.copy() font_tick.set_size('10') def cm2inch(*tupl): inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i / inch for i in tupl[0]) else: return tuple(i / inch for i in tupl) fontP = FontProperties() fontP.set_name('Arial') fontP.set_size(10) # fluxnet daily data path in_dir = 'D:/10.data/fluxnet2015_tier2_updated_Nov_3_2016/unzip_data/FLX_US-UMB_FLUXNET2015_SUBSET_2000-2014_1-3' # fluxnet daily data file (choose site have high quality data for all the year) fl = 'FLX_US-UMB_FLUXNET2015_SUBSET_DD_2000-2014_1-3.csv' in_file = "%s/%s" % (in_dir, fl) in_data = pd.read_csv(in_file) multi_year_GPP_NT = in_data['GPP_NT_VUT_REF'] #GPP_NT_VUT_REF multi_year_GPP_DT = in_data['GPP_DT_VUT_REF'] multi_year_NEE = in_data['NEE_VUT_REF'] multi_year_data_QC = in_data['NEE_VUT_REF_QC']
def plot(self, x='mjd', y='res', reserr=True, info=False, grid=False, resHist=False, savefig=False, figfilename='fig', figfiletype='png', bins=50, fontsize=15, alpha=1, yscalefac=1.5, years=False, plotbothres=True, useclassic=True, ylim=[]): """ Plot data of choice. """ from matplotlib.font_manager import FontProperties import matplotlib.pyplot as plt font = FontProperties() font.set_name('serif') # define axis-label dictionary. axlabel = { 'mjd': 'MJD', 'year': 'Year', 'res': r'TOA Residual ($\mu$s)', 'res_P': r'Pulse-number Residual', 'orb_phase': 'Orbital Phase', 'uncertainty': "Post-fit Residual Uncertainty ($\mu$s)" } # if desired, read in info.tmp file. info_flags = [] if (info): try: info_flags = np.loadtxt(info, dtype=str) except: sys.exit("Cannot read info-flag file.") # if desired, use classic look for matplotlib. if useclassic: plt.style.use('classic') fig, ax = plt.subplots() # generate the desired plot. if (resHist): ax.hist(getattr(self, 'res'), bins, alpha=alpha) else: x_data = getattr(self, x) y_data = getattr(self, y) # if desired x-axis is time in years, convert. if (x == 'mjd' and years): x = 'year' x_data = (x_data - 53005.) / 365.25 + 2004. if (y == 'res' and reserr): yerr_data = self.uncertainty if (info): color_count = 0 for label in np.unique(info_flags): x_data_int = x_data[(np.where(info_flags == label))[0]] y_data_int = y_data[(np.where(info_flags == label))[0]] yerr_data_int = yerr_data[(np.where(info_flags == label))[0]] color = colors_residuals[color_count] ax.errorbar(x_data_int, y_data_int, yerr=yerr_data_int, color=color, fmt='+') color_count += 1 else: ax.errorbar(x_data, y_data, yerr=yerr_data, fmt='+') else: plt.plot(x_data, y_data, 'b+') ax.set_xlabel(axlabel[x], fontproperties=font, fontsize=fontsize) ax.set_ylabel(axlabel[y], fontproperties=font, fontsize=fontsize) # add grids, if desired. if (grid): ax.grid() # now, set y-axis limits. ax.set_ylim(np.min(y_data) * yscalefac, np.max(y_data) * yscalefac) if (len(ylim) == 2): ax.ylim(ylim) if plotbothres: ax2 = ax.twinx() ax2.set_ylabel(axlabel['res_P'], fontproperties=font, fontsize=fontsize) ax2.set_ylim(np.min(self.res_P) * yscalefac, np.max(self.res_P) * yscalefac) plt.tight_layout() # save figure in png format, if desired. if savefig: plt.savefig(figfilename + '.' + figfiletype, fmt=figfiletype) plt.show()
def plot(self, x='mjd', y='res', reserr=True, info=False, grid=False, resHist=False, savefig=False, figfilename='fig', figfiletype='png', bins=50, fontsize=15, alpha=1, yscalefac=1.5, years=False, plotbothres=True, useclassic=True, ylim=[]): """ Plot data of choice. """ from matplotlib.font_manager import FontProperties import matplotlib.pyplot as plt font = FontProperties() font.set_name('serif') # define axis-label dictionary. axlabel = { 'mjd': 'MJD', 'year': 'Year', 'res': r'TOA Residual ($\mu$s)', 'res_P': r'Pulse-number Residual', 'orb_phase': 'Orbital Phase', 'uncertainty': "Post-fit Residual Uncertainty ($\mu$s)" } # if desired, read in info.tmp file. info_flags = [] if (info): try: info_flags = np.loadtxt(info, dtype=str) except: sys.exit("Cannot read info-flag file.") # if desired, use classic look for matplotlib. if useclassic: plt.style.use('classic') fig, ax = plt.subplots() # generate the desired plot. if (resHist): ax.hist(getattr(self, 'res'), bins, alpha=alpha) else: x_data = getattr(self, x) y_data = getattr(self, y) # if desired x-axis is time in years, convert. if (x == 'mjd' and years): x = 'year' x_data = (x_data - 53005.) / 365.25 + 2004. if (y == 'res' and reserr): yerr_data = self.uncertainty if (info): color_count = 0 for label in np.unique(info_flags): x_data_int = x_data[(np.where(info_flags == label))[0]] y_data_int = y_data[(np.where(info_flags == label))[0]] yerr_data_int = yerr_data[(np.where( info_flags == label))[0]] color = colors_residuals[color_count] ax.errorbar(x_data_int, y_data_int, yerr=yerr_data_int, color=color, fmt='+') color_count += 1 else: ax.errorbar(x_data, y_data, yerr=yerr_data, fmt='+') else: plt.plot(x_data, y_data, 'b+') ax.set_xlabel(axlabel[x], fontproperties=font, fontsize=fontsize) ax.set_ylabel(axlabel[y], fontproperties=font, fontsize=fontsize) # add grids, if desired. if (grid): ax.grid() # now, set y-axis limits. ax.set_ylim(np.min(y_data) * yscalefac, np.max(y_data) * yscalefac) if (len(ylim) == 2): ax.ylim(ylim) if plotbothres: ax2 = ax.twinx() ax2.set_ylabel(axlabel['res_P'], fontproperties=font, fontsize=fontsize) ax2.set_ylim( np.min(self.res_P) * yscalefac, np.max(self.res_P) * yscalefac) plt.tight_layout() # save figure in png format, if desired. if savefig: plt.savefig(figfilename + '.' + figfiletype, fmt=figfiletype) plt.show()
#! /usr/bin/python from matplotlib.font_manager import FontProperties from PSRpy.const import T_sun, d2r from PSRpy.parfile import DerivePar from pkcorr import doppler import matplotlib.pyplot as plt import numpy as np font = FontProperties() font.set_name('serif') def om1dot_m1m2(omd,omderr,a1,e,pb,om,m1,npts): """Calculate upper/lower bounds of OMDOT curve in the m1-m2 plane.""" m2omh = ((omd+omderr)*d2r*(1.-e**2)*(pb/2./np.pi)**(5./3.)/3./\ T_sun**(2./3.)/86400./365.25)**(3./2.) - m1 m2oml = ((omd-omderr)*d2r*(1.-e**2)*(pb/2./np.pi)**(5./3.)/3./\ T_sun**(2./3.)/86400./365.25)**(3./2.) - m1 return m2omh, m2oml def pbdot_m1m2(pbdot,pbdoterr,pb,e,m1,npts): """Calculate the upper/lower bounds of PBDOT curve in the m1-m2 plane.""" m2pbdh = np.zeros(npts) m2pbdl = np.zeros(npts) fe = 1.+73./24.*e**2+37./96.*e**4 A = -192.*np.pi/5.*(pb/2./np.pi)**(-5./3.)*fe*(1.-e**2)**(-7./2.)*\ T_sun**(5./3.) for i in range(npts): m2 = 1. # use Newton-Raphson method to get upper-bound curve.
import Plotting_Classes as ppion #plt.rc('font',**{'family':'sans-serif','sans-serif':['Bitstream Vera Sans']}) #plt.rc('text', usetex=True) #plt.rc('font',**{'size': 14}) #plt.rc('lines', linewidth=2) #plt.rcParams['mathtext.fontset'] = 'stixsans' #plt.rcParams['font.family'] = 'Bitstream Vera Sans' #plt.rcParams['mathtext.rm'] = 'stixsans' #plt.rcParams['mathtext.it'] = 'stixsans:italic' #plt.rcParams['mathtext.bf'] = 'stixsans:bold' plt.rcParams["font.weight"] = "normal" from matplotlib.font_manager import FontProperties font = FontProperties() font.set_family('sans-serif') font.set_name('stixsans') font.set_style('italic') font.set_weight('light') #solver="HLL" solver="HLLD" #solver="Roe" #solver="RCV" solver="NG" if solver=="HLL": files=["HLL_n100_0000.00000000.silo","HLL_n100_0000.00000412.silo","HLL_n100_0000.00000825.silo"] elif solver=="HLLD": files=["HLLD_n100_0000.00000000.silo","HLLD_n100_0000.00000825.silo","HLLD_n200_0000.00000000.silo","HLLD_n200_0000.00001646.silo"] elif solver=="RCV": files=["RCV_n100_0000.00000000.silo","RCV_n100_0000.00000412.silo","RCV_n100_0000.00000825.silo","RCV_n200_0000.00000000.silo","RCV_n200_0000.00000823.silo","RCV_n200_0000.00001646.silo","FieldLoop200l2_level00.00000000.silo"] elif solver=="NG":
ax.set_xlabel('time [s]', position=(0., 1e6), horizontalalignment='left') ax.set_ylabel('Damped oscillation [V]') plt.show() ############################################################################## # All the labelling in this tutorial can be changed by manipulating the # `matplotlib.font_manager.FontProperties` method, or by named kwargs to # `~matplotlib.axes.Axes.set_xlabel` from matplotlib.font_manager import FontProperties font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_style('italic') fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('time [s]', fontsize='large', fontweight='bold') ax.set_ylabel('Damped oscillation [V]', fontproperties=font) plt.show() ############################################################################## # Finally, we can use native TeX rendering in all text objects and have # multiple lines: fig, ax = plt.subplots(figsize=(5, 3))
def components(t, x): font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_size(12) x1 = x[0, :] x2 = x[1, :] x3 = x[2, :] x4 = x[3, :] x5 = x[4, :] x6 = x[5, :] x7 = x[6, :] x8 = x[7, :] x9 = x[8, :] x10 = x[9, :] x11 = x[10, :] x12 = x[11, :] x13 = x[12, :] x14 = x[13, :] # Working Volume plt.subplot(3, 5, 1) plt.plot(t, x1, 'b-') plt.xlabel('Time (day)') plt.ylabel('L') plt.title('Volume') # Si plt.subplot(3, 5, 2) plt.plot(t, x2, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Si') # Ss plt.subplot(3, 5, 3) plt.plot(t, x3, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Ss') # Si plt.subplot(3, 5, 4) plt.plot(t, x4, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Xi') # Xs plt.subplot(3, 5, 5) plt.plot(t, x5, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Xs') # Xbh plt.subplot(3, 5, 6) plt.plot(t, x6, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Xbh') # Xba plt.subplot(3, 5, 7) plt.plot(t, x7, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Xba') # Xp plt.subplot(3, 5, 8) plt.plot(t, x8, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Xp') # So plt.subplot(3, 5, 9) plt.ylim(0, 7.5) plt.plot(t, x9, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('So') # Sno plt.subplot(3, 5, 10) plt.plot(t, x10, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Sno') # Snh plt.subplot(3, 5, 11) plt.plot(t, x11, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Snh') # Snd plt.subplot(3, 5, 12) plt.plot(t, x12, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Snd') # Xnd plt.subplot(3, 5, 13) plt.plot(t, x13, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Xnd') # Salk plt.subplot(3, 5, 14) plt.plot(t, x14, 'b-') plt.xlabel('Time (day)') plt.ylabel('Concentration (ppm)') plt.title('Salk') plt.show()
def main(argv): parser = argparse.ArgumentParser( description='Analyse the distribution of MMPBSA/MMGBSA delta G') parser.add_argument( 'infile', help='input file containing energy totals (CSV format)') parser.add_argument('sumfile', help='summary file (text format)') parser.add_argument( 'trendfile', help='trend plot with confidence intervals (.png, .bmp, .pdf)') parser.add_argument( 'distfile', help='distribution plot of energy totals (.png, .bmp, .pdf)') parser.add_argument('-c', '--column', help='name of column to use (default TOTAL)') args = parser.parse_args() column = 'TOTAL' if not args.column else args.column global mean_results font = FontProperties() font.set_name('Calibri') font.set_size(28) means = [] with open(args.infile) as infile: reader = csv.DictReader(infile) for row in reader: if len(row[column]) > 0: means.append(float(row[column])) means = np.array(means) results_m = [] results_u = [] results_l = [] xs = [] with open(args.sumfile, 'w') as fo: for i in range(5, len(means) + 5, 5): if i >= 10000: print( 'Stopping after 10000 values due to limitations in the bootstrap function.' ) break mean_results = [] bounds = conf_intervals(means[:i]) fo.write("%d mean %0.2f +%0.2f -%0.2f\n" % (i, bounds[0], bounds[1], bounds[2])) results_m.append(bounds[0]) results_u.append(bounds[1] + bounds[0]) results_l.append(bounds[2] + bounds[0]) xs.append(i) plt.plot(xs, results_m, color='g') plt.plot(xs, results_u, linestyle='--', color='g') plt.plot(xs, results_l, linestyle='--', color='g') plt.locator_params(nbins=5, axis='y') plt.xlabel(u'Samples', fontproperties=font) plt.ylabel(u'\u0394G (kcal/mol)', fontproperties=font) plt.tight_layout() plt.savefig(args.trendfile) lim_l = round(bounds[0] - 2.5, 0) plt.xlim(lim_l, lim_l + 5) plt.ylim(0, 900) plt.locator_params(nbins=5, axis='y') plt.xlabel(u'Bootstrapped mean \u0394G (kcal/mol)', fontproperties=font) plt.ylabel(u'Frequency', fontproperties=font) plt.hist(mean_results, bins=50) plt.savefig(args.distfile)
def main(*, regenerate=False, parameters=settings.parameters): start_time = datetime.datetime.now() logging.info("LION debug letter experiment started: %s", start_time) common_info = get_common_info(parameters) results = dict() embedders = generate_all_embedders(common_info['dTSNE_mnist']) for embedder_name in embedders.keys(): process_single_embedder(embedder=embedders[embedder_name], embedder_name=embedder_name, results=results, regenerate=regenerate, common_info=common_info, parameters=parameters) end_time = datetime.datetime.now() logging.info("letter experiment ended: %s", end_time) logging.info("letter experiment duration: %s", end_time-start_time) _, _, lion_optimal_power = exp_lion_power_performance.load_lion_power_plot() lion_method_list = ["LION; $r_x$ at %dth perc.; $p$=%.1f" % (i, lion_optimal_power[i]) for i in sorted(lion_optimal_power)] lion90_name = [i for i in results.keys() if i.startswith('LION-90')][0] letters_y_lion90 = results[lion90_name]['EmbeddedPoints'] lion95_name = [i for i in results.keys() if i.startswith('LION-95')][0] letters_y_lion95 = results[lion95_name]['EmbeddedPoints'] lion99_name = [i for i in results.keys() if i.startswith('LION-99')][0] letters_y_lion99 = results[lion99_name]['EmbeddedPoints'] lion100_name = [i for i in results.keys() if i.startswith('LION-100')][0] letters_y_lion100 = results[lion100_name]['EmbeddedPoints'] cur_shown_letter_indices_begin = 0 cur_shown_letter_indices_end = 20 #for k in ['LION-90-16.4']: # embedders.keys(): # print(k ,embedders[k](common_info['letter_samples'] # [cur_shown_letter_indices_begin:cur_shown_letter_indices_end])) embedding_function = common_info['dTSNE_mnist'].generate_lion_tsne_embedder( function_kwargs={'radius_x_percentile': 90, 'power': 16.4}, random_state=90, verbose=2) #print(embedding_function( # common_info['letter_samples'][cur_shown_letter_indices_begin:cur_shown_letter_indices_end], verbose=2)) #print("\n\n\n") #print(letters_y_lion90[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, :]) Y_mnist = generate_data.load_y_mnist(parameters=parameters) point_size_gray = 10 point_size_interest = 15 plt.figure(dpi=300) plt.gcf().set_size_inches(6.8, 6.8) font_properties = FontProperties() font_properties.set_family('serif') font_properties.set_name('Times New Roman') font_properties.set_size(8) plt.scatter(Y_mnist[:, 0], Y_mnist[:, 1], c= 'gray', zorder=1, label=None, marker='.', s = point_size_gray) h1 = plt.scatter(letters_y_lion90[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 0], letters_y_lion90[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 1], c='red', zorder=1, label=None, marker='.', s = point_size_interest) h2 = plt.scatter(letters_y_lion95[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 0], letters_y_lion95[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 1], c='blue', zorder=1, label=None, marker='.', s = point_size_interest) h3 = plt.scatter(letters_y_lion99[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 0], letters_y_lion99[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 1], c='green', zorder=1, label=None, marker='.', s = point_size_interest) h4 = plt.scatter(letters_y_lion100[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 0], letters_y_lion100[cur_shown_letter_indices_begin:cur_shown_letter_indices_end, 1], c='purple', zorder=1, label=None, marker='.', s = point_size_interest) plt.legend([h1,h2,h3,h4], lion_method_list, ncol=1, prop=font_properties, borderpad=0.1,handlelength=2, columnspacing = 0, loc = 1, handletextpad=-0.7,frameon=True) plt.show()
# Startværdier #with open('Model_data_{}_{}_{}.csv'.format(file_name, fil, tid), 'w', newline = '') as csvfile: # filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) # for a in list(range(len(Q3_m))): # filewriter.writerow((Q3_m[a], Q4_m[a], Q2_m[a], Q1_m[a], Q0_m[a], Al5_m[a], Al4_m[a])) a = [0, 80] b = [0, 80] fitQ3 = np.polyfit(a, b, 1) fit_fn = np.poly1d(fitQ3) font = FontProperties() font.set_family('serif') font.set_name('Palatino Linotype') font.set_size('14') matplotlib.rcParams.update({ 'text.usetex': False, 'font.family': 'Palatino Linotype ', 'mathtext.fontset': 'cm', 'font.size': 14 }) #if fil == "Kapoor_2018": # # pltAl = [Al_data[0], Al_data[1], Al_data[2], Al_data[3], Al_data[4], Al_data[5]] # pltNa = [mod_data[6], mod_data[7], mod_data[8], mod_data[9], mod_data[10], mod_data[11], mod_data[12]] # # Al203 = np.array(pltAl)
ax.plot(x1, y1) ax.set_xlabel('time [s]', position=(0., 1e6), horizontalalignment='left') ax.set_ylabel('Damped oscillation [V]') plt.show() ############################################################################## # All the labelling in this tutorial can be changed by manipulating the # `matplotlib.font_manager.FontProperties` method, or by named kwargs to # `~matplotlib.axes.Axes.set_xlabel` from matplotlib.font_manager import FontProperties font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_style('italic') fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('time [s]', fontsize='large', fontweight='bold') ax.set_ylabel('Damped oscillation [V]', fontproperties=font) plt.show() ############################################################################## # Finally, we can use native TeX rendering in all text objects and have # multiple lines: fig, ax = plt.subplots(figsize=(5, 3))
def saveGraphs(self): """Multipage PDF output of groupData analysis""" self.gfilename = QFileDialog.getSaveFileName( self, "Save Group Analysis figures", os.path.expanduser("~"))[0] if self.gfilename: # from https://stackoverflow.com/a/31133424 Victor Juliet import datetime from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import matplotlib from matplotlib.font_manager import FontProperties matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['ps.fonttype'] = 42 font = FontProperties() #font.set_family('serif') font.set_name('Helvetica') # Create the PdfPages object to which we will save the pages: # The with statement makes sure that the PdfPages object is closed properly at # the end of the block, even if an Exception occurs. #df_list = [ v for k,v in self.groupsextracted_by_set.items()] fixedKeys = sanitizeList(self.groupsextracted_by_set.keys()) merged = pd.concat(self.groupsextracted_by_set.values(), axis=1, keys=fixedKeys) #merged.columns.levels[1] = merged.columns.levels[1] #print (merged.shape) #print (merged) #print (merged.columns.values) #print (merged.columns.levels[2]) #print (merged.columns.levels[1]) #print (merged.columns.levels[0]) All = slice(None) with PdfPages(self.gfilename + '.pdf') as pdf: for _ROI in list(merged.columns.levels[1]): # loop over ROIs # for each, if a group column exists then plot and use SD for shading # title by ROI, 6 per page? plt.figure(figsize=(4, 3)) plt.axes(ylim=(0, 1)) plt.xticks(fontname="Helvetica") plt.yticks(fontname="Helvetica") plt.title("ROI " + _ROI, fontproperties=font) for _set in list(merged.columns.levels[0]): #some indexes are not there if (_set, _ROI, 'mean') in list(merged.columns.values): SD = merged.loc[All, (_set, _ROI, 'SD')] m = merged.loc[All, (_set, _ROI, 'mean')] yn = pd.to_numeric(m - SD) yp = pd.to_numeric(m + SD) plt.plot(range(self.step), m, 'o-') #plt.plot(range(self.step), m, 'k') plt.fill_between( [float(x) for x in range(self.step)], yn, yp, alpha=0.5, facecolor='#FF9848') #edgecolor='#CC4F1B', pdf.savefig() # saves the current figure into a pdf page plt.close() # We can also set the file's metadata via the PdfPages object: d = pdf.infodict() d['Title'] = 'PDF of graphs from SAFT' #d['Author'] d['Subject'] = 'group peak analysis' #d['CreationDate'] d['ModDate'] = datetime.datetime.today() print("PDF output complete.")
sampled_z = np.array(nu_traces[:,:,numiter-1] > 0.95,dtype=float) ey = (np.dot(x,np.dot(sampled_z,phi_mean_traces[:,:,numiter-1]))); np.savetxt(output_dir+"est_y.csv", ey, delimiter=",") rank = np.sum(((np.sum(sampled_z > threshold,axis=0)>0) * (np.sum(phi_mean_traces[:,:,numiter-1]> threshold,axis=1)>0))); f = open(output_dir+"rank.csv",'w') f.write(str(rank)) f.close() f = open(output_dir+"metrics.csv", 'w'); f.write(str(rss)+","+str(cv)+","+str(rank)); f.close(); # Plot and Save the Convergence and Results if (makeplots==1): fontP = FontProperties(); fontP.set_name('Arial') plt.clf(); plt.imshow(nu_traces[:,:,numiter-1].T,interpolation='none') plt.colorbar() plt.ylabel('Factor') plt.xlabel('SNP') plt.title('Estimated Z') plt.savefig(output_dir+'EstimatedZ.png') plt.clf(); plt.imshow(phi_mean_traces[:,:,numiter-1].T,interpolation='none') plt.colorbar() plt.ylabel('Gene') plt.xlabel('Factor') plt.title('Estimated A')
def __init_axis_labels(self): font = FontProperties() font.set_family(self.family) font.set_name(self.name) font.set_style('italic') return font
def plot_trial_steps(self): '''Plot target (sig-eps-curve of the tensile test) and trial curves and corresponding phi function together with trail steps from the iteration process. NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values within the global variables 'phi_trial_list_n' and 'sig_trial_list_n' n - index of the time steps to be considered i - index of the iteration steps performed in order to fit the target curve ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() # font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman # font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif # font.cursive : Zapf Chancery # font.monospace : Courier, Computer Modern Typewriter font.set_name('Script MT') # name = ['Times New Roman', 'Helvetica', 'Script MT'] #? font.set_family('serif') # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'] font.set_style('normal') # style = ['normal', 'italic', 'oblique'] font.set_size('small') # size = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11'] font.set_variant('normal') # variant= ['normal', 'small-caps'] font.set_weight('medium') # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] #------------------------------------------------------------------- p.figure(facecolor='white', dpi=600, figsize=(8, 6)) # white background # time list corresponding to the specified numbers of steps and step size # step_list = [n * self.step_size for n in range(self.n_steps + 1)] # get list of lists containing the trial values of 'sig_app' and 'phi_trail' # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled # within the iteration process when the method 'get_lack_of_fit" is called # phi_trial_list_n = [[1.]] + self.phi_trial_list_n sig_trial_list_n = [[0.]] + self.sig_trial_list_n xrange = 10. # plotting range for strain [mm/m] yrange = 15. # plotting range for stress [MPa] for n in range(self.n_steps): for i in range(len(phi_trial_list_n[n + 1])): x = np.array([step_list[n], step_list[n + 1]]) eps = 1000. * x # plot strains in permil on the x-axis #-------------------------------------- # sig-eps trial #-------------------------------------- # plot the numerically calculated sig-eps-curve (tensile test) # (with trial steps) # sig_trail = np.array( [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]]) p.subplot(222) p.plot(eps, sig_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange], fontproperties=font) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) #-------------------------------------- # phi_trail #-------------------------------------- # plot the fitted phi-function # (with trial steps) # p.subplot(224) phi_trail = np.array( [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]]) p.plot(eps, phi_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.1f" % x, locs), fontproperties=font) #-------------------------------------- # sig-eps target #-------------------------------------- # plot the sig-eps-target curve (tensile test) # p.subplot(221) eps = 1000. * self.mfn_line_array_target.xdata[:-1] sig_target = self.mfn_line_array_target.ydata[:-1] p.plot(eps, sig_target, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange]) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) #-------------------------------------- # phi_trail (final) #-------------------------------------- # plot the corresponding fitted phi-function # (without trial steps) # p.subplot(223) eps = 1000. * self.fitted_phi_fn.xdata[:-1] phi_fn = self.fitted_phi_fn.ydata[:-1] p.plot(eps, phi_fn, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, map(lambda x: "%.0f" % x, locs), fontproperties=font) locs, labels = p.yticks() p.yticks(locs, map(lambda x: "%.1f" % x, locs), fontproperties=font) # save figure with calibration process in directory # "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png" simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn') if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) ctt_key = self.test_key filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.pdf') p.savefig(filename) print 'plot_trail_steps.png saved to file %s' % (filename) filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.png') p.savefig(filename, dpi=600) print 'plot_trail_steps.png saved to file %s' % (filename) p.show()
class M1M2(): def __init__(self, inobj, npts=200, font_name="serif", om1s=[False, False, False], pkcorr='n'): """ Calculate upper/lower bounds of post-Keplerian (PK)parameters and store all arrays in a single object. Currently supported PK parameters are: PBDOT, OMDOT, GAMMA, r, s. Required argument: - 'inobj' = input parfile object, which can be generated by using the "readpar" class in the 'psrpar.py' module. Default arguments: - 'npts' = number of array elements for upper/lower bounds. - 'pkcorr' = correct for Doppler bias? (y = yes, n = no). - 'om1s' = list of values for a geodetic-precession measurement. (median value, lower uncertainy, upper uncertainy.) """ self.font = FontProperties() self.font.set_name(font_name) a1, e, pb, om = inobj.A1, inobj.E, inobj.PB * 86400., inobj.OM m1 = 3. * np.arange(npts) / (npts - 1.) setattr(self, 'm1', m1) m2omh = m2oml = np.zeros(npts) # if OMDOT and its error are set, calculate m1m2 arrays. if (hasattr(inobj, 'OMDOT') and hasattr(inobj, 'OMDOTerr')): omdot, omdoterr = inobj.OMDOT, inobj.OMDOTerr m2omh, m2oml = om1dot_m1m2(omdot, omdoterr, a1, e, pb, om, m1, npts) setattr(self, 'OMDOT_U', m2omh) setattr(self, 'OMDOT_L', m2oml) # if GAMMA and its error are set, calculate m1m2 arrays. if (hasattr(inobj, 'GAMMA') and hasattr(inobj, 'GAMMAerr')): gamma, gammaerr = inobj.GAMMA, inobj.GAMMAerr m2gamh, m2gaml = gamma_m1m2(gamma, gammaerr, e, pb, m1, npts) setattr(self, 'GAMMA_U', m2gamh) setattr(self, 'GAMMA_L', m2gaml) # if Shapiro-r and its error are set, calculate m1m2 arrays. if (hasattr(inobj, 'M2') and hasattr(inobj, 'M2err')): r, rerr = inobj.M2, inobj.M2err m2rh, m2rl = r_m1m2(r, rerr, npts) setattr(self, 'r_U', m2rh) setattr(self, 'r_L', m2rl) # if Shapiro-s and its error are set, calculate m1m2 arrays. if (hasattr(inobj, 'SINI') and hasattr(inobj, 'SINIerr')): s, serr = inobj.SINI, inobj.SINIerr m2sh, m2sl = s_m1m2(s, serr, a1, pb, m1, npts) setattr(self, 's_U', m2sh) setattr(self, 's_L', m2sl) # if PBDOT and its error are set, calculate m1m2 arrays. if (hasattr(inobj, 'PBDOT') and hasattr(inobj, 'PBDOTerr')): pbdot, pbdoterr = inobj.PBDOT, inobj.PBDOTerr if (pkcorr == 'y'): der = DerivePar(inobj) b, l, mu, muerr = der.gal_b, der.gal_l, der.mu, der.muerr corr, corr_err = doppler(0.7, 0.3, b, l, mu, muerr) corr *= inobj.PB * 86400. * 1e12 corr_err *= inobj.PB * 86400. * 1e12 pbdot -= sum(corr) pbdoterr = np.sqrt(pbdoterr**2 + corr_err**2) m2pbdh, m2pbdl = pbdot_m1m2(pbdot, pbdoterr, pb, e, m1, npts) setattr(self, 'PBDOT_U', m2pbdh) setattr(self, 'PBDOT_L', m2pbdl) # if OM1SPIN and the uncertainties are set, calculate m1m2 arrays. if (any(om1s)): om1smed = om1s[0] om1serr = om1s[1:] print(om1serr) m2om1sh, m2om1sl = om1spin_m1m2(om1smed, om1serr, pb, e, m1, npts) setattr(self, 'OM1SPIN_U', m2om1sh) setattr(self, 'OM1SPIN_L', m2om1sl) def plot(self, labels={}): """Plot availabe m1-m2 data using the matplotlib package.""" if (hasattr(self, 'OMDOT_U') and hasattr(self, 'OMDOT_L')): #plt.plot(self.m1,self.OMDOT_U,'k-') #plt.plot(self.m1,self.OMDOT_L,'k-') plt.fill_between(self.m1, self.OMDOT_U, self.OMDOT_L, color='k', alpha=0.8) plt.text(2.0, 0.4, r'$\dot{\omega}$', fontproperties=self.font, fontsize=15) if (hasattr(self, 'GAMMA_U') and hasattr(self, 'GAMMA_L')): #plt.plot(self.m1,self.GAMMA_U,'g-') #plt.plot(self.m1,self.GAMMA_L,'g-') plt.text(0.2, 1.0, r'$\gamma$', fontproperties=self.font, fontsize=15) plt.fill_between(self.m1, self.GAMMA_U, self.GAMMA_L, color='g', alpha=0.8) if (hasattr(self, 'r_U') and hasattr(self, 'r_L')): #plt.plot(self.m1,self.r_U,'r-') #plt.plot(self.m1,self.r_L,'r-') plt.fill_between(self.m1, self.r_U, self.r_L, color='r', alpha=0.5) plt.text(2.7, 1.2, r'$r$', fontproperties=self.font, fontsize=15) if (hasattr(self, 's_U') and hasattr(self, 's_L')): #plt.plot(self.m1,self.s_U,'m-') #plt.plot(self.m1,self.s_L,'m-') plt.fill_between(self.m1, self.s_U, self.s_L, color='m', alpha=0.5) plt.text(0.5, 0.7, r'$s$', fontproperties=self.font, fontsize=15) if (hasattr(self, 'PBDOT_U') and hasattr(self, 'PBDOT_L')): #plt.plot(self.m1,self.PBDOT_U,'b-') #plt.plot(self.m1,self.PBDOT_L,'b-') plt.fill_between(self.m1, self.PBDOT_U, self.PBDOT_L, color='blue', alpha=0.5) plt.text(1.3, 2.5, r'$\dot{P}_{\rm b}$', fontproperties=self.font, fontsize=15) if (hasattr(self, 'OM1SPIN_U') and hasattr(self, 'OM1SPIN_L')): #plt.plot(self.m1,self.OM1SPIN_U,'y-') #plt.plot(self.m1,self.OM1SPIN_L,'y-') plt.fill_between(self.m1, self.OM1SPIN_U, self.OM1SPIN_L, color='yellow', alpha=0.7) plt.text(2.5, 2.3, r'$\Omega_1^{\rm spin}$', fontproperties=self.font, fontsize=15) plt.xlim(0., 3.) plt.ylim(0., 3.) plt.axes().set_aspect('equal') plt.xlabel(r'Pulsar Mass (${\rm M}_{\odot}$)', fontproperties=self.font, fontsize=15) plt.ylabel(r'Companion Mass (${\rm M}_{\odot}$)', fontproperties=self.font, fontsize=15) plt.savefig('m1m2.png', dpi=500, fmt='png') plt.show()
class Plugin(): def Clear(self): if hasattr(self, 'coverPanel'): self.coverPanel.Show(False) self.frameBox.Show(False) self.createButton.Show(False) def CoverInit(self): self.coverPanel = wx.Panel(self.bigPanel, -1, pos = (0, 0), size = (self.bPSize[0] - 277, self.bPSize[1] - 8)) self.coverPanel.Show(True) fs = self.frame.GetSize() self.frameBox = wx.ScrolledWindow(self.frame, -1, pos = (2, 80), size = (fs[0] - 10, fs[1] - 120), style = wx.VSCROLL|wx.BORDER_SUNKEN) self.frameBox.SetBackgroundColour('WHITE') self.frameBox.Show(True) self.plotter = mpl.PlotNotebook(self.coverPanel,pos = (-50, 0), size = (self.bPSize[0] - 227, self.bPSize[1] - 8)) self.coverPanel.SetBackgroundColour('GRAY') self.axes1 = self.plotter.add('figure 1').gca() def FrameBoxFill(self): yPos = 5 for opt in self.options: if '\n' in opt[1]: yp = yPos - 3 else: yp = yPos + 3 dummy = wx.StaticText(self.frameBox, -1, opt[1], pos=(3,yp)) opt[2].SetSize((self.frameBox.GetSize()[0] - 80, -1)) osi = opt[2].GetSize() if not osi[1] == 21: opt[2].SetPosition((57, yPos + (21-osi[1])/2)) else: opt[2].SetPosition((57, yPos)) opt[2].SetValue(opt[3]) yPos += 30 def OptionsInit(self): tb = ['probability','entropy'] self.options = [['lines','Number\nof lines:', wx.SpinCtrl(self.frameBox, -1),1], ['units','Units:', wx.ComboBox(self.frameBox,-1,choices=tb, style=wx.CB_READONLY),tb[1]], ['start','Start res.:', wx.TextCtrl(self.frameBox, -1, "",),'1'], ['end','Final res.:', wx.TextCtrl(self.frameBox, -1, "",), str(len(self.rec[0].seq))], ['title','Title:', wx.TextCtrl(self.frameBox, -1, ""),'']] self.FrameBoxFill() def Colors(self): self.colorDict = {'A':'b', 'C':'c', 'D':'r', 'E':'r', 'F':'b', 'G':'k', 'H':'y', 'I':'b', 'K':'y', 'L':'b', 'M':'b', 'N':'g', 'P':'k', 'Q':'g', 'R':'y', 'S':'g', 'T':'g', 'V':'b', 'W':'b', 'Y':'b', 'U':'m', 'O':'m', 'B':'g', 'Z':'g', 'J':'b', 'X':'w', ' ':'w', '.':'k', '-':'k'} def MessageDia(self, string): dialog = wx.MessageDialog(self.frame, string, 'Error', style=wx.OK) dialog.ShowModal() dialog.Destroy() def CreateRecMat(self): self.recMat = [] for seq in self.rec[0].seq: self.recMat.append([]) for record in self.rec: for i,r in enumerate(record.seq): self.recMat[i].append(r) def CharSort(self): self.sort = [] for r in self.recMat: self.sort.append([]) temp = dict() chars = dict() sumV = 0 for c in r: if not c in chars.keys(): chars[c] = 0. chars[c] += 1. for c in chars.keys(): if not chars[c] in temp.keys(): temp[chars[c]] = [] sumV += chars[c] temp[chars[c]].append(c) i = len(r) while i > 1: if i in temp.keys(): for x in temp[i]: self.sort[-1].append([x,i]) i -= 1 self.sort[-1].append(sumV) def DoEnt(self): figWidth = self.bPSize[0] - 277 xPos = 0 yPos = 0 seqLen = int(self.options[3][2].GetValue()) seqLen -= int(self.options[2][2].GetValue()) numLines = self.options[0][2].GetValue() cpr = seqLen / self.options[0][2].GetValue() if seqLen % self.options[0][2].GetValue() > 0: cpr += 1 for i,s in enumerate(self.sort[:-1]): sV = s[-1] if i%cpr == 0: yPos = 1 - (int(i / cpr + 1) * 1. / numLines) xPos = 0 yp = yPos for c in s[:-1]: fs = 720.*c[1]/sV*figWidth/473./seqLen*(numLines**.99) self.axes1.text(xPos, yp, c[0], fontsize = fs, color = self.colorDict[c[0]], ha = 'left', fontproperties = self.font, va = 'bottom') yp += fs / 200. xPos += 2.*s[0][1]/sV*figWidth/473./seqLen*.7*(numLines**.8) def ShowImage(self, event): self.axes1.clear() self.plotter.remove() self.plotter.Show(False) self.axes1 = self.plotter.add('figure 1').gca() self.font = FontProperties() self.font.set_name('Georgia') self.recMat = [] self.CreateRecMat() self.CharSort() if self.options[1][2].GetValue() == 'entropy': self.DoEnt() else: self.DoProb() self.axes1.set_ylim(0,1) #self.axes1.set_xlim(0,len(self.rec[0].seq)) self.axes1.axis('off') self.plotter.resize([3.05 / 244, 3.05 / 244]) self.plotter.Show(True) def GetExec(self, fr, bp, rec, cL): self.frame = fr self.bigPanel = bp self.bPSize = bp.GetSize() self.colorList = cL self.rec = rec self.CoverInit() self.OptionsInit() self.Colors() self.createButton = wx.Button(self.frame, -1, "CREATE", pos = (5,self.frame.GetSize()[1] - 35), size = (self.frame.GetSize()[0] - 10,25)) self.frame.Bind(wx.EVT_BUTTON, self.ShowImage, self.createButton) self.frameBox.SetScrollbars(0, 1, 0, len(self.options)*30+13) self.frameBox.SetScrollRate(15, 35)
def plot(): plt.figure(dpi=320, figsize=(15, 7)) font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') x = [0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5] bleu = [ 43.33, 9.1, 27.6, 32.05, 31, 33, 14, 15, 16.42, 3.19, 5.33, 33.63, 0.87, 2.16 ] x_coord = [0, 1, 2, 3, 4, 5] x_labels = [ '[2]\n2017', '[5]\n2017', '[6]\n2019', '[1]\n2019', '[3]\n2019', '[4]\n2019' ] plt.text(x[0] + 0.1, bleu[0] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[1] + 0.1, bleu[1] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[2] + 0.1, bleu[2] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[3] + 0.1, bleu[3] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[4] + 0.1, bleu[4] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[5] + 0.1, bleu[5] - 1, 'HMM', { 'color': 'black', 'fontsize': 22 }) plt.text(x[6] + 0.1, bleu[6] - 2, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[7] + 0.1, bleu[7] - 1, 'HMM', { 'color': 'black', 'fontsize': 22 }) plt.text(x[8] + 0.1, bleu[8], 'NNGen', {'color': 'black', 'fontsize': 22}) plt.text(x[9] + 0.1, bleu[9] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[10] + 0.1, bleu[10] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[11] + 0.1, bleu[11] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[12] + 0.1, bleu[12] - 1, 'NMT', { 'color': 'black', 'fontsize': 22 }) plt.text(x[13] + 0.1, bleu[13], 'NNGen', { 'color': 'black', 'fontsize': 22 }) colors = [ 'darkred', 'green', 'green', 'green', 'red', 'red', 'lightsalmon', 'lightsalmon', 'lightsalmon', 'peachpuff', 'blue', 'darkred', 'silver', 'silver' ] scale = np.array([450 for _ in range(len(x))]) plt.scatter(x=x, y=bleu, s=scale, c=colors, marker='^') plt.yticks(fontsize=20) plt.xlim(-0.3, 5.7) plt.xticks(x_coord, x_labels, fontsize=20) plt.grid(axis='y', alpha=0.75) plt.xlabel("Статьи", fontsize=25) plt.ylabel("BLEU", fontsize=28) plt.show()
from matresdev.db.matdb.trc.ccs_unit_cell import \ CCSUnitCell, DamageFunctionEntry from matresdev.db.simdb import \ SimDB from matresdev.db.simdb.simdb_class import \ SimDBClass, SimDBClassExt simdb = SimDB() from pickle import dump, load from matplotlib.font_manager import FontProperties font = FontProperties() font.set_name('Script MT') font.set_family('serif') font.set_style('normal') font.set_size('large') font.set_variant('normal') font.set_weight('medium') def format_plot(axes, xlim=None, ylim=None, xlabel='', ylabel=''): '''format 2d-plot black and with with times legends ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties()
def Cap_vs_cycles(self, set_fig=False, save_fig=False): """ Initialize from a :class:`.Supercap`. Notes ----- Plotting capacitance against cycle and saving it as 'current mA_cap_vs_cycles_datetime.png' Parameter ---------- set_fig : :class:`bool`, optional Changing the setting of the figure save_fig : :class:`bool`, optional whether the figure will be saved Return ------ A figure of capacitance over cycle number """ if set_fig == True: length = float(input('Please input length for the figure:')) width = float(input('Please input width for the figure:')) label_size = float( input('Please input the font size for the figure:')) lw = float(input('Please input the line width for the figure:')) clr = input('Please input the line colour for the figure:') else: length = 20 width = 15 label_size = 40 lw = 5 clr = 'black' figure(figsize(length, width)) ax = gca() for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(label_size) label.set_family('sans-serif') label.set_name('Arial') tx = ax.yaxis.get_offset_text() tx.set_fontsize(label_size) tx.set_family('sans-serif') tx.set_name('Arial') font = FontProperties() font.set_family('sans-serif') font.set_name('Arial') font.set_size(label_size + 10) xlabel('Number of cycles', fontproperties=font) if self.error is False: ylabel('Non-gravimetric capacitance $F$', fontproperties=font) else: ylabel('Capacitance $F g^{-1}$', fontproperties=font) plot(range(1, self.cycle_n - len(self.faulty_cycles) + 1), self.cap_ls, color=clr, linewidth=lw) if save_fig is True: savefig( str(self.current) + 'mA_cap_vs_cycles_' + 'Date{0:%d%m}_Time{0:%I_%M}'.format(datetime.datetime.now()) + '.png', transparent=True) else: pass
def Show_dV2(self, cycle_check=False, zoom_in=False): """ Initialize from a :class:`.Supercap`. Notes ----- Visualising the second derivative and the charge/discharge curve of a specified cycle with the option of changing the ESR analysis method used for calculating esr_ls Parameters ---------- cycle_check : :class:`int`, optional The method for ESR analysis. Specify the cycle of the charge/discharge curve and the second derivative to be plotted on the same axes input: a interger between 0 and the total number of cycles setting : :class:`float`, optional The setting for ESR analysis setting = the cut off second derivative being used in the ESR_method. (setting = 1 for ESR_method = 1 or 2) Return ------ A plot of charge discharge curve and the corresponding second derivative :class:`.Supercap`, optional self.esr_ls """ if self.esr_method[0] != 2 and self.esr_method[0] != 201: print( 'The current ESR method is neither 2 or 201. Please change the ESR method to constant second derivative analysis using .ESR_method_change().' ) return False else: pass if cycle_check is False: cycle_check = int( input( 'Of which cycle would you like to see the second derivative? enter a number between 1 and ' + str(self.cycle_n))) else: pass proceed = True cycle_check -= 1 while proceed is True: if cycle_check in self.faulty_cycles: cycle_check = int( input( 'The cycle enteres is a faulty cycle. Please enter another number between 1 and ' + str(self.cycle_n))) cycle_check -= 1 else: proceed = False setting = self.esr_method[1] while proceed is False: print('The cut off second derivative currently being used is ' + str(setting)) esr_dV2 = [ ESR_dv2(self.t_ls, self.V_ls, self.peaks[i], self.troughs[i], set_deriv=setting)[1] for i in range(self.cycle_n) ] num_pt = [ ESR_dv2(self.t_ls, self.V_ls, self.peaks[i], self.troughs[i], set_deriv=setting)[2] for i in range(self.cycle_n) ] peak1 = self.peaks[cycle_check] trough1 = self.troughs[cycle_check] num1 = num_pt[cycle_check] dV_ls1 = esr_dV2[cycle_check] t_ls1 = array(self.t_ls[peak1:trough1]) - self.t_ls[peak1] V_ls1 = self.V_ls[peak1:trough1] if zoom_in is False: zoom_in = int(floor(len(t_ls1) / 2)) figure(figsize(20, 15)) fig, ax1 = plt.subplots() font = FontProperties() font.set_family('sans-serif') font.set_name('Arial') font.set_size(35) color = 'tab:red' ax1.set_xlabel('Time (s)', fontproperties=font) ax1.set_ylabel('Second derivative $ dV^2/dt $', color=color, fontproperties=font) ax1.plot(t_ls1[1:zoom_in - 2], dV_ls1[:zoom_in - 3], linewidth=5, marker='x', ms=12, mew=5, color=color) ax1.plot(t_ls1[num1 + 2], dV_ls1[num1 + 1], linewidth=5, marker='x', ms=20, mew=6, color='g') ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx( ) # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel( 'Voltage (V)', color=color, fontproperties=font) # we already handled the x-label with ax1 ax2.plot(t_ls1[:zoom_in - 2], V_ls1[:zoom_in - 2], linewidth=5, marker='x', ms=12, mew=5, color=color) ax2.plot(t_ls1[num1 + 1], V_ls1[num1 + 1], linewidth=5, marker='x', ms=20, mew=6, color='g') ax2.tick_params(axis='y', labelcolor=color) ax = gca() for label in ax1.get_xticklabels() + ax1.get_yticklabels( ) + ax2.get_yticklabels(): label.set_fontsize(30) label.set_family('sans-serif') label.set_name('Arial') show() opinion = input('Are you happy with the cut off point? (yes/no)') if opinion == 'yes': proceed = True change_setting = input( 'Do you wish to change the cut off point to the current value? (setting =' + str(setting) + ')[yes/no]') if change_setting == 'yes': self.ESR_method_change(ESR_method=201, setting=setting) break else: setting = float( input( 'Please input the value of desired cut off second derivative.' ))
def main(argv): parser = argparse.ArgumentParser(description='Analyse the distribution of MMPBSA/MMGBSA delta G') parser.add_argument('infile', help='input file containing energy totals (CSV format)') parser.add_argument('sumfile', help='summary file (text format)') parser.add_argument('trendfile', help='trend plot with confidence intervals (.png, .bmp, .pdf)') parser.add_argument('distfile', help='distribution plot of energy totals (.png, .bmp, .pdf)') parser.add_argument('-c', '--column', help='name of column to use (default TOTAL)') args = parser.parse_args() column = 'TOTAL' if not args.column else args.column global mean_results font = FontProperties() font.set_name('Calibri') font.set_size(28) means = [] with open(args.infile) as infile: reader = csv.DictReader(infile) for row in reader: if len(row[column]) > 0: means.append(float(row[column])) means = np.array(means) results_m = [] results_u = [] results_l = [] xs = [] with open(args.sumfile, 'w') as fo: for i in range(5, len(means)+5, 5): if i >= 10000: print('Stopping after 10000 values due to limitations in the bootstrap function.') break mean_results = [] bounds = conf_intervals(means[:i]) fo.write("%d mean %0.2f +%0.2f -%0.2f\n" % (i, bounds[0], bounds[1], bounds[2])) results_m.append(bounds[0]) results_u.append(bounds[1]+bounds[0]) results_l.append(bounds[2]+bounds[0]) xs.append(i) plt.plot(xs, results_m, color='g') plt.plot(xs, results_u, linestyle='--', color='g') plt.plot(xs, results_l, linestyle='--', color='g') plt.locator_params(nbins=5, axis='y') plt.xlabel(u'Samples', fontproperties=font) plt.ylabel(u'\u0394G (kcal/mol)', fontproperties=font) plt.tight_layout() plt.savefig(args.trendfile) lim_l = round(bounds[0] - 2.5, 0) plt.xlim(lim_l, lim_l+5) plt.ylim(0, 900) plt.locator_params(nbins=5, axis='y') plt.xlabel(u'Bootstrapped mean \u0394G (kcal/mol)', fontproperties=font) plt.ylabel(u'Frequency', fontproperties=font) plt.hist(mean_results, bins=50) plt.savefig(args.distfile)
dpi = 288 dpi3 = 864 png_out_dir=('/mnt/raid/wrf-chem/wrfchem_v415/cbars') # print('rain Colourbar hh') #New lines to overwrite previous colour scheme palette=['w', 'lightcyan', 'paleturquoise', 'turquoise', 'lightskyblue', 'royalblue', 'orange', 'orangered', 'firebrick', 'darkmagenta'] #cmap.set_under('w') #cm=LinearSegmentedColormap.from_list('palette', palette, N=len(palette)) cmap=plt.cm.gnuplot2 font = FontProperties() font.set_name('Ariel') #cm.set_over('purple') #cmap.set_over('#5B2C6F') #bounds=[0, .01, .1, .25, .5, 1, 2.5, 5, 10, 20, 50, 100] #bounds=[0, .1, .3, .5, .7, 1.0, 2.0, 3.0, 6.0, 12.0] bounds=[0.0001, 0.1, .3, .5, .7, 1.0, 2.0, 3.0, 6.0, 12.0, 400] norm = mc.BoundaryNorm(bounds, 256) #norm=mpl.colors.BoundaryNorm(bounds, cmap.N) cbar_png_out_path=(png_out_dir+'/rain_cbar_gnuplot2.png') fig=plt.figure(figsize=(10, 1)) #add_axes(Left, bottom, width, height) #ax2=fig.add_axes([0.0001, 0.05, 0.15, 0.85]) ##Rectange((x,y, width, height)) #ax2.add_patch(patches.Rectangle((0.00001, 0.0001), 0.9999, 0.9999, color='black', linewidth='0', label='None') ) #ax2.annotate(' Rain (mm/hr)', (0.001, 0.5), color='white', weight='bold', fontsize=18)
def gcmdiff_plots(tbl, out_file): with PdfPages(out_file) as pdf: font0 = FontProperties() font0.set_name('sans-serif') font0.set_size(8) font1 = font0.copy() font1.set_size(9) font2 = font0.copy() font2.set_size(11) fig = plt.figure(1, figsize=(8, 11)) for i, v in enumerate(tbl.columns.values[1:4]): ax = fig.add_subplot(3, 1, i + 1) p = ax.plot(tbl.loc[:, 'AbsCor'].values, tbl.loc[:, v].values, 'k-o') title = v ax.set_title(title, fontproperties=font2) ax.invert_xaxis() plt.setp(list(ax.spines.values()), lw=0.5, color="#666666") plt.setp(ax.get_xticklabels(), fontproperties=font1) plt.setp(ax.get_yticklabels(), fontproperties=font1) plt.setp(ax.xaxis.get_ticklines(), markersize=3) plt.setp(ax.yaxis.get_ticklines(), markersize=3) plt.setp(ax.xaxis.get_ticklines(minor=True), markersize=1) plt.setp(ax.yaxis.get_ticklines(minor=True), markersize=1) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') plt.close() pdf.savefig(fig) fig = plt.figure(1, figsize=(8, 11)) for i, v in enumerate(tbl.columns.values[4:6]): ax = fig.add_subplot(3, 1, i + 1) p = ax.plot(tbl.loc[:, 'AbsCor'].values, tbl.loc[:, v].values, 'k-o') title = v ax.set_title(title, fontproperties=font2) ax.invert_xaxis() plt.setp(list(ax.spines.values()), lw=0.5, color="#666666") plt.setp(ax.get_xticklabels(), fontproperties=font1) plt.setp(ax.get_yticklabels(), fontproperties=font1) plt.setp(ax.xaxis.get_ticklines(), markersize=3) plt.setp(ax.yaxis.get_ticklines(), markersize=3) plt.setp(ax.xaxis.get_ticklines(minor=True), markersize=1) plt.setp(ax.yaxis.get_ticklines(minor=True), markersize=1) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') plt.close() pdf.savefig(fig) fig = plt.figure(1, figsize=(8, 11)) for i, v in enumerate(tbl.columns.values[6:8]): ax = fig.add_subplot(3, 1, i + 1) p = ax.plot(tbl.loc[:, 'AbsCor'].values, tbl.loc[:, v].values, 'k-o') title = v ax.set_title(title, fontproperties=font2) ax.invert_xaxis() plt.setp(list(ax.spines.values()), lw=0.5, color="#666666") plt.setp(ax.get_xticklabels(), fontproperties=font1) plt.setp(ax.get_yticklabels(), fontproperties=font1) plt.setp(ax.xaxis.get_ticklines(), markersize=3) plt.setp(ax.yaxis.get_ticklines(), markersize=3) plt.setp(ax.xaxis.get_ticklines(minor=True), markersize=1) plt.setp(ax.yaxis.get_ticklines(minor=True), markersize=1) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') plt.close() pdf.savefig(fig)
from matplotlib import patches from matplotlib.font_manager import FontProperties from matplotlib import pyplot as plt import numpy as np from pandas import read_csv font24 = FontProperties() font24.set_family('sans-serif') font24.set_name('Liberation Sans') #'Helvetica' font24.set_size(24) font18 = font24.copy() font18.set_size(18) font36 = font24.copy() font36.set_size(36) data = read_csv("out_age.csv") zz = data['n'] N = len(zz) def make_plot(x_name, x_label, y_name, y_label, title): fig,ax = plt.subplots(figsize=(14.3,7)) max_y = np.ceil(max(data[y_name])+1) plt.xlim(28,105); plt.ylim(-1, max_y) #(0,33) #plt.subplots_adjust(.09,.12,.995,.91) dx = 105 - 28 dy = max_y + 6 #6 instead of 1, hack, not sure why it works maxd = max(dx, dy) for i in range(N):
def plot_trial_steps(self): '''Plot target (sig-eps-curve of the tensile test) and trial curves and corresponding phi function together with trail steps from the iteration process. NOTE: the global variable 'rec_trial_steps' must be set to 'True' in order to store the iteration values within the global variables 'phi_trial_list_n' and 'sig_trial_list_n' n - index of the time steps to be considered i - index of the iteration steps performed in order to fit the target curve ''' #------------------------------------------------------------------- # configure the style of the font to be used for labels and ticks #------------------------------------------------------------------- # from matplotlib.font_manager import FontProperties font = FontProperties() # font.serif : Times, Palatino, New Century Schoolbook, Bookman, Computer Modern Roman # font.sans-serif : Helvetica, Avant Garde, Computer Modern Sans serif # font.cursive : Zapf Chancery # font.monospace : Courier, Computer Modern Typewriter font.set_name('Script MT') # name = ['Times New Roman', 'Helvetica', 'Script MT'] #? font.set_family('serif') # family = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'] font.set_style('normal') # style = ['normal', 'italic', 'oblique'] font.set_size('small') # size = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '11'] font.set_variant('normal') # variant= ['normal', 'small-caps'] font.set_weight('medium') # weight = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black'] #------------------------------------------------------------------- p.figure(facecolor='white', dpi=600, figsize=(8, 6)) # white background # time list corresponding to the specified numbers of steps and step size # step_list = [n * self.step_size for n in range(self.n_steps + 1)] # get list of lists containing the trial values of 'sig_app' and 'phi_trail' # the lists are defined as global variables of 'MATSCalibDamageFn' and are filled # within the iteration process when the method 'get_lack_of_fit" is called # phi_trial_list_n = [[1.]] + self.phi_trial_list_n sig_trial_list_n = [[0.]] + self.sig_trial_list_n xrange = 10. # plotting range for strain [mm/m] yrange = 15. # plotting range for stress [MPa] for n in range(self.n_steps): for i in range(len(phi_trial_list_n[n + 1])): x = np.array([step_list[n], step_list[n + 1]]) eps = 1000. * x # plot strains in permil on the x-axis #-------------------------------------- # sig-eps trial #-------------------------------------- # plot the numerically calculated sig-eps-curve (tensile test) # (with trial steps) # sig_trail = np.array( [sig_trial_list_n[n][-1], sig_trial_list_n[n + 1][i]]) p.subplot(222) p.plot(eps, sig_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange], fontproperties=font) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.0f" % x for x in locs], fontproperties=font) #-------------------------------------- # phi_trail #-------------------------------------- # plot the fitted phi-function # (with trial steps) # p.subplot(224) phi_trail = np.array( [phi_trial_list_n[n][-1], phi_trial_list_n[n + 1][i]]) p.plot(eps, phi_trail, color='k', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.1f" % x for x in locs], fontproperties=font) #-------------------------------------- # sig-eps target #-------------------------------------- # plot the sig-eps-target curve (tensile test) # p.subplot(221) eps = 1000. * self.mfn_line_array_target.xdata[:-1] sig_target = self.mfn_line_array_target.ydata[:-1] p.plot(eps, sig_target, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('stress $\sigma$ [MPa]', fontproperties=font) if self.format_ticks: # format ticks for plot p.axis([0, xrange, 0., yrange]) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.0f" % x for x in locs], fontproperties=font) #-------------------------------------- # phi_trail (final) #-------------------------------------- # plot the corresponding fitted phi-function # (without trial steps) # p.subplot(223) eps = 1000. * self.fitted_phi_fn.xdata[:-1] phi_fn = self.fitted_phi_fn.ydata[:-1] p.plot(eps, phi_fn, color='black', linewidth=1) p.xlabel(r'strain $\varepsilon$ [1E-3]', fontproperties=font) p.ylabel('integrity $\phi$ [-]', fontproperties=font) if self.format_ticks: # format ticks for plot p.yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0]) p.axis([0, xrange, 0., 1.]) locs, labels = p.xticks() p.xticks(locs, ["%.0f" % x for x in locs], fontproperties=font) locs, labels = p.yticks() p.yticks(locs, ["%.1f" % x for x in locs], fontproperties=font) # save figure with calibration process in directory # "/simdb/simdata/lcc_table/output_images/save_fig_to_file.png" simdata_dir = os.path.join(simdb.simdata_dir, 'mats_calib_damage_fn') if os.path.isdir(simdata_dir) == False: os.makedirs(simdata_dir) ctt_key = self.test_key filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.pdf') p.savefig(filename) print('plot_trail_steps.png saved to file %s' % (filename)) filename = os.path.join(simdata_dir, ctt_key + self.param_key + '.png') p.savefig(filename, dpi=600) print('plot_trail_steps.png saved to file %s' % (filename)) p.show()
import matplotlib.pyplot as plt import generate_data from matplotlib.font_manager import FontProperties labels_mnist = generate_data.load_labels_mnist() Y_mnist = generate_data.load_y_mnist() plt.figure(dpi=300) font_properties = FontProperties() font_properties.set_family('serif') font_properties.set_name('Times New Roman') font_properties.set_size(9) plt.xlim([-180, 180]) plt.ylim([-150, 170]) plt.gcf().set_size_inches( 2.5, 2.1) #Let's set the plot sizes that just fit paper margins legend_list = list() for l in set(sorted(labels_mnist)): plt.scatter(Y_mnist[labels_mnist == l, 0], Y_mnist[labels_mnist == l, 1], marker='.', s=5) legend_list.append(str(l)) #plt.title("MNIST Dataset - TSNE visualization") #plt.tight_layout() l = plt.legend(legend_list, bbox_to_anchor=(0.99, 1.025), markerscale=8,
from matplotlib import patches from matplotlib.font_manager import FontProperties font24 = FontProperties() font24.set_family('sans-serif') font24.set_name('Helvetica') font24.set_size(24) font18 = font24.copy() font18.set_size(18) font36 = font24.copy() font36.set_size(36) outage0 = [] out_withd0 = [] with open("out_age.csv",'r') as filename1: for l in filename1: outage0.append(l.strip('\n').split(',')) with open("out_withd.csv",'r') as filename2: for l in filename2: out_withd0.append(l.strip('\n').split(',')) outage1 = array([(int(x),float(y),int(z)) for x,y,z in outage0[1:]]) out_withd1 = array([(int(x),float(y),int(z)) for x,y,z in out_withd0[2:]]) N = len(outage1) xx = outage1[:,0]
from datatools import batch_data, loadFromH5, buileToH5 from model import FCN_Handnet from modeltools import * import tensorflow as tf import tensorlayer as tl import win_unicode_console, os import matplotlib.pyplot as plt import numpy as np from matplotlib.font_manager import FontProperties win_unicode_console.enable() font_axis = FontProperties() font_axis.set_family('serif') font_axis.set_name('Times New Roman') font_axis.set_style('italic') font_axis.set_size(20) font_title = FontProperties() font_title.set_family('serif') font_title.set_name('Times New Roman') font_title.set_style('italic') font_title.set_size(25) def findmax(label, imgsize=48): m = label.shape[0] label_flat = label.reshape(m, imgsize**2) index = np.argmax(label_flat, axis=1)[:, np.newaxis] return np.concatenate([index // imgsize, index % imgsize], axis=1)
def Check_analysis(self, begin=False, end=False, set_fig=False, save_fig=False): """ Initialize from a :class:`.Supercap`. Notes ----- Plotting the charge/discharge curve and visualising how the data is analysed (indicate the slope fitting for capacitance and the voltage drop for ESR) Parameter ---------- begin: :class:`int`, optional The first cycle to be visualised end : :class:`int`, optional The last cycle to be visualised set_fig : :class:`bool`, optional Changing the setting of the figure save_fig : :class:`bool` or `str`, optional save_fig = False, the plot will not be saved save_fig = True, the plot will be saved as 'Check_analysis_[datetime].png' save_fig = class:`str` , the plot will be saved as 'the input string.png' Return ------ A plot of the charge/discharge curve with liniearly fitted slope and voltage drop """ if begin is False or end is False: print( 'Please enter the first cycle number for the check, the cycle number should be an interger between 1 and ' + str(self.cycle_n)) if begin is False: begin = int( input('Please enter the first cycle number for the check')) else: pass if end is False: end = int( input('Please enter the last cycle number for the check')) else: pass if set_fig == True: length = float(input('Please input length for the figure:')) width = float(input('Please input width for the figure:')) label_size = float( input('Please input the font size for the figure:')) lw = float(input('Please input the line width for the figure:')) ms = float(input('Please input the marker size for the figure:')) mew = float( input('Please input the marker weight for the figure:')) degrees = float( input('Please input the rotation degrees for the x ticks:')) else: length = 10 width = 7 label_size = 30 lw = 5 ms = 25 mew = 5 degrees = 45 figure(figsize(length, width)) ax = gca() for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(label_size) label.set_family('sans-serif') label.set_name('Arial') tx = ax.xaxis.get_offset_text() tx.set_fontsize(label_size) tx.set_family('sans-serif') tx.set_name('Arial') if begin is 1: plot(self.t_ls[0:self.troughs[end - 1]], self.V_ls[0:self.troughs[end - 1]], label=str(self.current) + ' mA', linewidth=lw, c='black') else: plot(self.t_ls[self.troughs[begin - 2]:self.troughs[end - 1]], self.V_ls[self.troughs[begin - 2]:self.troughs[end - 1]], label=str(self.current) + ' mA', linewidth=lw, c='black') mid_ind = [ Half_pt_ind( self.V_ls[self.peaks[i]:self.troughs[i]], (self.V_ls[self.peaks[i]] + self.V_ls[self.troughs[i]]) / 2) for i in range(len(self.peaks)) ] for i in range(begin - 1, end): if i + 1 in self.faulty_cycles: print('Cycle ' + str(i + 1) + ' was skipped for calculation due to errors') else: peaki = self.peaks[i] troughi = self.troughs[i] ipeakx = self.t_ls[peaki] itroughx = self.t_ls[troughi] if self.cap_method is 1: fit = polyfit(self.t_ls[peaki:troughi][mid_ind[i]:], self.V_ls[peaki:troughi][mid_ind[i]:], 1, cov=True)[0] fitx = linspace(ipeakx * 0.8 + itroughx * 0.2, itroughx, 20) fity = fitx * fit[0] + fit[1] plot(fitx, fity, linewidth=lw, linestyle='--', color='red') plot([ ipeakx + 0.035 * (itroughx - ipeakx) * (end - begin + 1) ] * 100, linspace( self.V_ls[peaki], self.V_ls[peaki] - self.esr_ls[i] * 2 * self.current * 10**(-3), 100), color='b', linewidth=lw, linestyle=':') plot(ipeakx, self.V_ls[peaki] - self.esr_ls[i] * 2 * self.current * 10**(-3), linestyle='', marker=1, ms=ms, mew=mew, color='b') plot(ipeakx, self.V_ls[peaki], linestyle='', marker=1, ms=ms, mew=mew, color='b') plot(self.t_ls[peaki:troughi][mid_ind[i]], self.V_ls[peaki:troughi][mid_ind[i]], linestyle='', marker='+', ms=ms, mew=mew, color='r') plot(itroughx, self.V_ls[troughi], linestyle='', marker='+', ms=ms, mew=mew, color='r') else: fit = polyfit(self.t_ls[peaki:troughi][:mid_ind[i]], self.V_ls[peaki:troughi][:mid_ind[i]], 1, cov=True)[0] fitx = linspace(1.4 * ipeakx - 0.4 * itroughx, ipeakx * 0.45 + itroughx * 0.55, 20) fity = fitx * fit[0] + fit[1] plot(fitx, fity, linewidth=lw, linestyle='--', color='red') plot([ ipeakx + 0.035 * (itroughx - ipeakx) * (end - begin + 1) ] * 100, linspace( self.V_ls[peaki], self.V_ls[peaki] - self.esr_ls[i] * 2 * self.current * 10**(-3), 100), color='b', linewidth=lw, linestyle=':') plot(ipeakx, self.V_ls[peaki] - self.esr_ls[i] * 2 * self.current * 10**(-3), linestyle='', marker=1, ms=ms, mew=mew, color='b') plot(ipeakx, self.V_ls[peaki], linestyle='', marker=1, ms=ms, mew=mew, color='b') plot(self.t_ls[peaki:troughi][mid_ind[i]], self.V_ls[peaki:troughi][mid_ind[i]], linestyle='', marker='+', ms=ms, mew=mew, color='r') plot(ipeakx, self.V_ls[peaki], linestyle='', marker='+', ms=ms, mew=mew, color='r') font = FontProperties() font.set_family('sans-serif') font.set_name('Arial') font.set_size(label_size + 5) xticks(rotation=degrees) xlabel('Time (s)', fontproperties=font) ylabel('Voltage (V)', fontproperties=font) font.set_size(label_size) legend(fontsize=label_size) if save_fig == True: savefig( 'Check_analysis_' + 'Date{0:%d%m}_Time{0:%I_%M}_'.format(datetime.datetime.now()) + '.png', transparent=True) elif save_fig == False: pass else: savefig(str(save_fig) + '.png', transparent=True)