def show_dag(self, expand=set()): """Generate and show a DAG for the model """ from matplotlib.pyplot import show as pltshow G = self.make_dag(expand=expand) with warnings.catch_warnings(): warnings.simplefilter("ignore") ## Plotting edge_labels = dict([(( u, v, ), d["label"]) for u, v, d in G.edges(data=True)]) n = G.size() ## Manual layout # if n == 2: if False: pos = { "(var)": [-0.5, +0.5], "(out)": [+0.5, -0.5], } pos[self.functions[0].name] = [+0.5, +0.5] ## Optimized layout else: try: ## Planar, if possible pos = nx.planar_layout(G) except nx.NetworkXException: ## Scaled spring layout pos = nx.spring_layout( G, k=0.6 * n, pos={ "(Inputs)": [-0.5 * n, +0.5 * n], "(Outputs)": [+0.5 * n, -0.5 * n], }, fixed=["(var)", "(out)"], threshold=1e-6, iterations=100, ) # Generate colormap color_map = [] for node in G: if G.nodes[node]["parent"] == self.name: color_map.append("blue") else: color_map.append("green") # Draw nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw(G, pos, node_size=1000, with_labels=True, node_color=color_map) pltshow()
def multiplot(datax, datay, show=True, **kwargs): """ Plot multiple y-axis and possible multiple curves in each. Result is saved\ as a '.png' document. Parameters ---------- datax : list of floats x-axis values. datay : list of floats or list of tuples of list of floats y-axis values per axis and per curve in each axis, if tuple. labels : list, optional list of or tupple of list of curve labels (the default is None). unitx : str, optional x-axis label (the default is None). unity : list of str, optional y-axis labels per axis (the default is None). limits= : list of tuples, optional List of (ymin, ymax) values. If None then (ymin, ymax) is set \ automatically. If 'extend', the y-axis is extend by 5% on both ends (the default is \ 'extend'). linewidth : float, optional The default is 2. figsize : tuple of float, optional The default is (5., 5.). filelabel : str, optional Figure is saved in 'filelabel.png' if provided (the default is None). loc : int or string or pair of floats, default: 0 The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= log : list of str, optional Log-scale activation for each axis according to =============== ============= Plot type Code =============== ============= 'plot' '' 'semilogx' 'x' 'semilogy' 'y' 'loglog' 'xy' =============== ============= linestyles : iterable, otpional List of line styles; the default is ('-b', '--r', ':g', '-.m'). fontsize : int, optional the default is figsize[0]*4 legendfontsize : int, optional Figure legend font size. If None then set to 4/5 of fontsize (the \ default is None). maintitle : str, optional Figure main title. If set to None, the desactivated (the default is \ None). axedef : tuple of floats, optional Figure geometry (left, botom, right, top, height, width). The default is (.15, .15, .85, .85, .1, .3). ====== \ =============================================================== Value Description ====== \ =============================================================== left the left side of the subplots of the figure. bottom the bottom of the subplots of the figure. right the right side of the subplots of the figure. top the top of the subplots of the figure. wspace the amount of width reserved for blank space between subplots. hspace the amount of height reserved for white space between \ subplots. ====== \ =============================================================== markersize : float Default is 6. markeredgewidth : float Width of line around markers (the default is 0.5). nbinsx, nbinsy : int, optional number of x-axis and y-axis ticks (the default is 4). minor : bool Activate the minor grid. xpos_ylabel : float, optional If provided, set the x-position of the ylabels so that they align (the\ default is None). You probably want it to be negative. """ opts = standard.copy() opts.update(kwargs) nplots = len(datay) if opts['fontsize'] is None: opts['fontsize'] = int(6*opts['figsize'][0]) if opts['legendfontsize'] is None: opts['legendfontsize'] = int(0.8*opts['fontsize']) if opts['unity'] is None: opts['unity'] = ['', ]*nplots if opts['limits'] is None: opts['limits'] = [None, ]*nplots elif opts['limits'] == 'extend': opts['limits'] = ['extend', ]*nplots if opts['labels'] is None: opts['labels'] = [None, ] * nplots if opts['log'] is None: opts['log'] = ['', ] * nplots from matplotlib.pyplot import subplots, close close('all') fig, axs = subplots(nplots, 1, sharex=True, figsize=opts['figsize']) activate_latex(opts) # Dic of font properties from matplotlib.pyplot import rc rc('font', size=opts['fontsize'], **globalfonts()) x = dec(datax, opts) for n in range(nplots): miny = float('Inf') maxy = -float('Inf') if type(datay[n]) is list: y = dec(datay[n], opts) maxy = max([maxy, max(y)]) miny = min([miny, min(y)]) if nplots > 1: plotn = whichplot(opts['log'][n], axs[n]) else: plotn = whichplot(opts['log'][n], axs) plotn(x, y, opts['linestyles'][0], label=opts['labels'][n], linewidth=opts['linewidth'], markeredgewidth=opts['markeredgewidth'], markersize=opts['markersize']) elif isinstance(datay[n], tuple): len_yn = len(datay[n]) if opts['labels'][n] is None: opts['labels'][n] = (None, )*len_yn for m in range(len_yn): if isinstance(opts['labels'][n][m], (list, tuple)): annotate(x, y, opts['labels'][n][m][0], opts['labels'][n][m][1], opts['legendfontsize']) l = None else: l = opts['labels'][n][m] y = dec(datay[n][m]) maxy = max([maxy, max(y)]) miny = min([miny, min(y)]) plotn = whichplot(opts['log'][n], axs[n]) plotn(x, y, opts['linestyles'][m], label=l, linewidth=opts['linewidth'], markersize=opts['markersize'], markeredgewidth=opts['markeredgewidth']) setlims(axs[n], x, miny, maxy, opts['limits'][n]) setticks(axs[n], opts, n) axs[n].legend(loc=opts['loc'], fontsize=opts['legendfontsize']) if opts['unity'][n] is not None: axs[n].set_ylabel(opts['unity'][n], fontsize=opts['fontsize']) if opts['xpos_ylabel'] is not None: axs[n].yaxis.set_label_coords(opts['xpos_ylabel'], 0.5) if n == nplots-1: axs[n].set_xlabel(opts['unitx'], fontsize=opts['fontsize']) else: from matplotlib.pyplot import setp setp(axs[n].get_xticklabels(), visible=False) if opts['maintitle'] is not None: from matplotlib.pyplot import suptitle suptitle(opts['maintitle']) if opts['axedef'] is not None: print(opts['axedef']) left, right = opts['axedef'][0], opts['axedef'][2] bottom, top = opts['axedef'][1], opts['axedef'][3] wspace, hspace = opts['axedef'][4], opts['axedef'][5] fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top, wspace=wspace, hspace=hspace) else: fig.tight_layout(pad=0.6, w_pad=0.5, h_pad=.0) if opts['filelabel'] is not None: from matplotlib.pyplot import savefig savefig(opts['filelabel'] + '.' + opts['format']) if show: from matplotlib.pyplot import show as pltshow pltshow()
def spectrogram(x, fs, show=False, **kwargs): """ Plot spectrogramm of datay. Parameters ---------- x : lists of values y-axis values for each curve. fs : floats samplerate. label : list, optional signal label (the default is None). xlabel : str, optional x-axis label (the default is None). ylabel : list of str, optional y-axis labels (the default is None). path : str, optional Figure is saved in 'filelabel.png' (the default is 'multiplot'). title : str, optional Figure main title. If set to None, the desactivated (the default is None). dynamics : positive value, optional The dynamics is normalized to 0db and the value below minus 'dynamics' are set to zeros cmap : str, optional Colormap specifier. Default is 'gnuplot2'. """ opts = standard.copy() opts['ylabel'] = opts.pop('ylabels') opts['label'] = opts.pop('labels') opts.update(kwargs) if not 'dynamics' in opts.keys(): opts['dynamics'] = 80. if not 'nfft' in opts.keys(): opts['nfft'] = int(2**8) else: opts['nfft'] = int(opts['nfft']) if not 'cmap' in opts.keys(): opts['cmap'] = 'BuPu' from matplotlib.pyplot import figure, fignum_exists i = 1 while fignum_exists(i): i += 1 fig = figure(i) from matplotlib.pyplot import axes ax = axes() if isinstance(opts['label'], (list, tuple)): annotate(*opts['label'], ax=ax) noverlap = int(opts['nfft']/2) Pxx, fbins, tbins, im = ax.specgram(np.array(x)/(opts['nfft']/2.), mode='psd', Fs=fs, NFFT=opts['nfft'], noverlap=noverlap, cmap=opts['cmap']) Pxx = Pxx/np.max(Pxx) extent = [tbins.min(), tbins.max(), 0., fbins.max()] print(extent) im = ax.imshow(10*np.log10(Pxx), extent=extent, origin='lower', aspect='auto', cmap=opts['cmap'], vmin=-opts['dynamics'], vmax=0) if opts['xlabel'] is not None: from matplotlib.pyplot import xlabel xlabel(opts['xlabel']) if opts['ylabel'] is not None: from matplotlib.pyplot import ylabel ylabel(opts['ylabel']) if opts['title'] is not None: from matplotlib.pyplot import title title(opts['title']) if opts['path'] is not None: from matplotlib.pyplot import savefig savefig(opts['path'] + '.' + opts['format']) fig.colorbar(im, label='Magnitude (dB)') if opts['log'] is not None and 'y' in opts['log']: from matplotlib.pyplot import yscale yscale('log') if opts['log'] is not None and 'x' in opts['log']: from matplotlib.pyplot import xscale xscale('log') if show: from matplotlib.pyplot import show as pltshow pltshow()
def singleplot(x, y, show=True, **kwargs): """ Plot multiple y-axis and possible multiple curves in each. Result is saved\ as a '.png' document. Parameters ---------- x : list of numerics x-axis values. y : list of lists of numerics y-axis values for each curves curve. labels : list, optional list of curve labels (the default is None). The number of labels must be a divisor of the number of plots. xlabel : str, optional x-axis label (the default is None). ylabel : str, optional y-axis label (the default is None). path : str, optional Figure is saved in 'path.ext' if provided (the default is None). See 'format' agument for extension. format : str, optional Extension in {'pdf', 'png'} for figure export. If not given, the extension from pyphs.config.py is used. loc : int or string or pair of floats, default: 0 The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= log : str, optional Log-scale activation according to =============== ============= Plot type Code =============== ============= 'plot' '' 'semilogx' 'x' 'semilogy' 'y' 'loglog' 'xy' =============== ============= linestyles : iterable, otpional List of line styles; the default is ('-b', '--r', ':g', '-.m'). title : str, optional Figure main title. If set to None, the desactivated (the default is \ None). grid = bool Indicate whether to show the grid or not (the default is False) """ opts = standard.copy() opts['ylabel'] = opts.pop('ylabels') opts.update(kwargs) try: if (isinstance(y[0], (float, int)) or (isinstance(y[0], numpy.ndarray) and len(y[0].shape) == 0)): y = [y] except IndexError: pass nplots = int(y.__len__()) if opts['labels'] is None: opts['labels'] = [None, ]*nplots elif len(opts['labels']) != nplots: nlabels = len(opts['labels']) if nplots % nlabels == 0: N = nplots - nlabels opts['labels'] = list(opts['labels']) + [None, ]*N if opts['log'] is None: opts['log'] = '' from matplotlib.pyplot import figure, fignum_exists i = 1 while fignum_exists(i): i += 1 fig = figure(i) from matplotlib.pyplot import axes ax = axes() ax.ticklabel_format(style='sci', scilimits=(-2, 2)) print_legend = False for n, yn in enumerate(y): if len(yn) == 0: print('Skipping empty array: ', opts['labels'][n]) continue if isinstance(opts['labels'][n], (list, tuple)): annotate(*opts['labels'][n], ax=ax) l = None else: l = opts['labels'][n] print_legend = l is not None or print_legend plot = whichplot(opts['log'], ax) if opts['linestyles'] is not None: plot(x, yn, opts['linestyles'][n], label=l) else: plot(x, yn, label=l) if print_legend: from matplotlib.pyplot import legend legend(loc=opts['loc']) if opts['xlabel'] is not None: from matplotlib.pyplot import xlabel xlabel(opts['xlabel']) if opts['ylabel'] is not None: from matplotlib.pyplot import ylabel ylabel(opts['ylabel']) if opts['title'] is not None: from matplotlib.pyplot import title title(opts['title']) # Show grid ax.grid(opts['grid']) ax.minorticks_on() if opts['path'] is not None: from matplotlib.pyplot import savefig savefig(opts['path'] + '.' + opts['format']) if show: from matplotlib.pyplot import show as pltshow pltshow() return fig, ax
def spectrogram(x, fs, show=False, **kwargs): """ Plot spectrogramm of datay. Parameters ---------- x : lists of values y-axis values for each curve. fs : floats samplerate. label : list, optional signal label (the default is None). xlabel : str, optional x-axis label (the default is None). ylabel : list of str, optional y-axis labels (the default is None). path : str, optional Figure is saved in 'filelabel.png' (the default is 'multiplot'). title : str, optional Figure main title. If set to None, the desactivated (the default is None). dynamics : positive value, optional The dynamics is normalized to 0db and the value below minus 'dynamics' are set to zeros cmap : str, optional Colormap specifier. Default is 'gnuplot2'. """ opts = standard.copy() opts['ylabel'] = opts.pop('ylabels') opts['label'] = opts.pop('labels') opts.update(kwargs) if not 'dynamics' in opts.keys(): opts['dynamics'] = 80. if not 'nfft' in opts.keys(): opts['nfft'] = int(2**8) else: opts['nfft'] = int(opts['nfft']) if not 'cmap' in opts.keys(): opts['cmap'] = 'BuPu' from matplotlib.pyplot import figure, fignum_exists i = 1 while fignum_exists(i): i += 1 fig = figure(i) from matplotlib.pyplot import axes ax = axes() if isinstance(opts['label'], (list, tuple)): annotate(*opts['label'], ax=ax) noverlap = int(opts['nfft'] / 2) Pxx, fbins, tbins, im = ax.specgram(np.array(x) / (opts['nfft'] / 2.), mode='psd', Fs=fs, NFFT=opts['nfft'], noverlap=noverlap, cmap=opts['cmap']) Pxx = Pxx / np.max(Pxx) extent = [tbins.min(), tbins.max(), 0., fbins.max()] im = ax.imshow(10 * np.log10(Pxx), extent=extent, origin='lower', aspect='auto', cmap=opts['cmap'], vmin=-opts['dynamics'], vmax=0) if opts['xlabel'] is not None: from matplotlib.pyplot import xlabel xlabel(opts['xlabel']) if opts['ylabel'] is not None: from matplotlib.pyplot import ylabel ylabel(opts['ylabel']) if opts['title'] is not None: from matplotlib.pyplot import title title(opts['title']) if opts['path'] is not None: from matplotlib.pyplot import savefig savefig(opts['path'] + '.' + opts['format']) fig.colorbar(im, label='Magnitude (dB)') if opts['log'] is not None and 'y' in opts['log']: from matplotlib.pyplot import yscale yscale('log') if opts['log'] is not None and 'x' in opts['log']: from matplotlib.pyplot import xscale xscale('log') if show: from matplotlib.pyplot import show as pltshow pltshow()
def multiplot(x, y, show=True, **kwargs): """ Plot multiple y-axis and possible multiple curves in each. Result can be saved as a '.png' document. Parameters ---------- x : list of floats x-axis values. y : list of floats or of tuples of list of floats y-axis values per axis and per curve in each axis, if tuple. xlabel : str, optional x-axis label (the default is None). ylabels : list of str, optional y-axis label for each axe (the default is None). title : str, optional Figure main title. Desactivated if set to None (default). labels : list, optional list of curve labels (the default is None). Textboxes can be used with_files the elements syntax ['label', (xrel, yrel)] where xrel and yrel are relative x and y position. path : str, optional Figure is saved in 'path.ext' if provided (the default is None). Extension from pyphs config.py. loc : int or string or pair of floats, default: 0 The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= log : list of str, optional Log-scale activation for each axis according to =============== ============= Plot type Code =============== ============= 'plot' '' 'semilogx' 'x' 'semilogy' 'y' 'loglog' 'xy' =============== ============= linestyles : iterable, otpional List of line styles; the default is None. xpos_ylabel : float, optional If provided, set the x-position of the ylabels so that they align (the default is None). You probably want it to be negative. grid : bool Indicate whether to show the grid or not. """ # ------------------------------------------------------------ # Number of axes nplots = len(y) # ------------------------------------------------------------ # Recover standard options opts = standard.copy() # Update with new options opts.update(kwargs) # ------------------------------------------------------------ # Check fo options length if opts['ylabels'] is None: opts['ylabels'] = [ '', ] * nplots elif not len(opts['ylabels']) == nplots: raise AttributeError('wrong number of y labels') if opts['labels'] is None: opts['labels'] = [ None, ] * nplots elif not len(opts['ylabels']) == nplots: raise AttributeError('wrong number of curves labels') if opts['log'] is None: opts['log'] = [ '', ] * nplots elif not len(opts['log']) == nplots: raise AttributeError('wrong number of log options') # ------------------------------------------------------------ # Init figure and axes from matplotlib.pyplot import subplots, fignum_exists i = 1 while fignum_exists(i): i += 1 fig, axs = subplots(nplots, 1, sharex=True, num=i) # ------------------------------------------------------------ # Iterate over y data for n, yn in enumerate(y): # -------------------------------------------------------- # get axe if nplots > 1: axe = axs[n] else: axe = axs axe.ticklabel_format(style='sci', scilimits=(-2, 2)) # -------------------------------------------------------- # flag print_legend = False # -------------------------------------------------------- # if yn is a list of values if (isinstance(yn[0], (float, int)) or (isinstance(yn[0], numpy.ndarray) and len(yn[0].shape) == 0)): # get plot in {plot, semilogx, semilogy, loglog} plotn = whichplot(opts['log'][n], axe) # Add label or annotation if isinstance(opts['labels'][n], (list, tuple)): annotate(*opts['labels'][n], ax=axe) l = None else: l = opts['labels'][n] print_legend = l is not None or print_legend # Plot if opts['linestyles'] is not None: plotn(x, yn, opts['linestyles'][n][0], label=l) else: plotn(x, yn, label=l) # -------------------------------------------------------- # if yn is a list of signals else: # get number of signals in yn len_yn = len(yn) # Set appropriate len of labels if opts['labels'][n] is None: opts['labels'][n] = (None, ) * len_yn elif not len(opts['labels'][n]) == len_yn: raise AttributeError('wrong number of labels') # iterate over yn data for m, ynm in enumerate(yn): # Add label or annotation if isinstance(opts['labels'][n][m], (list, tuple)): annotate(*opts['labels'][n][m], ax=axe) l = None else: l = opts['labels'][n][m] print_legend = l is not None or print_legend # get plot in {plot, semilogx, semilogy, loglog} plotn = whichplot(opts['log'][n], axe) # Plot if opts['linestyles'] is not None: plotn(x, ynm, opts['linestyles'][n][m], label=l) else: plotn(x, ynm, label=l) # -------------------------------------------------------- # Print legend if print_legend: axs[n].legend(loc=opts['loc']) # -------------------------------------------------------- # Set y label if opts['ylabels'][n] is not None: axs[n].set_ylabel(opts['ylabels'][n]) if opts['xpos_ylabel'] is not None: axs[n].yaxis.set_label_coords(opts['xpos_ylabel'], 0.5) # -------------------------------------------------------- # Set x label if last plot if n == nplots - 1: axs[n].set_xlabel(opts['xlabel']) else: from matplotlib.pyplot import setp setp(axs[n].get_xticklabels(), visible=False) # -------------------------------------------------------- # Show grid axs[n].grid(opts['grid']) axs[n].minorticks_on() # ------------------------------------------------------------ # Set title if opts['title'] is not None: from matplotlib.pyplot import suptitle suptitle(opts['title']) # ------------------------------------------------------------ # Save file if opts['path'] is not None: from matplotlib.pyplot import savefig savefig(opts['path'] + '.' + opts['format']) # ------------------------------------------------------------ # Show if show: from matplotlib.pyplot import show as pltshow pltshow() return fig, axs
def singleplot(x, y, show=True, **kwargs): """ Plot multiple y-axis and possible multiple curves in each. Result is saved\ as a '.png' document. Parameters ---------- x : list of numerics x-axis values. y : list of lists of numerics y-axis values for each curves curve. labels : list, optional list of curve labels (the default is None). xlabel : str, optional x-axis label (the default is None). ylabel : str, optional y-axis label (the default is None). path : str, optional Figure is saved in 'path.ext' if provided (the default is None). Extension from pyphs config.py. loc : int or string or pair of floats, default: 0 The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= log : str, optional Log-scale activation according to =============== ============= Plot type Code =============== ============= 'plot' '' 'semilogx' 'x' 'semilogy' 'y' 'loglog' 'xy' =============== ============= linestyles : iterable, otpional List of line styles; the default is ('-b', '--r', ':g', '-.m'). title : str, optional Figure main title. If set to None, the desactivated (the default is \ None). grid = bool Indicate whether to show the grid or not (the default is False) """ opts = standard.copy() opts['ylabel'] = opts.pop('ylabels') opts.update(kwargs) if (isinstance(y[0], (float, int)) or (isinstance(y[0], numpy.ndarray) and len(y[0].shape) == 0)): y = [y] nplots = int(y.__len__()) if opts['labels'] is None: opts['labels'] = [None, ]*nplots if opts['log'] is None: opts['log'] = '' from matplotlib.pyplot import figure, fignum_exists i = 1 while fignum_exists(i): i += 1 fig = figure(i) from matplotlib.pyplot import axes ax = axes() ax.ticklabel_format(style='sci', scilimits=(-2, 2)) print_legend = False for n, yn in enumerate(y): if len(yn) == 0: print('Skipping empty array: ', opts['labels'][n]) continue if isinstance(opts['labels'][n], (list, tuple)): annotate(*opts['labels'][n], ax=ax) l = None else: l = opts['labels'][n] print_legend = l is not None or print_legend plot = whichplot(opts['log'], ax) if opts['linestyles'] is not None: plot(x, yn, opts['linestyles'][n], label=l) else: plot(x, yn, label=l) if print_legend: from matplotlib.pyplot import legend legend(loc=opts['loc']) if opts['xlabel'] is not None: from matplotlib.pyplot import xlabel xlabel(opts['xlabel']) if opts['ylabel'] is not None: from matplotlib.pyplot import ylabel ylabel(opts['ylabel']) if opts['title'] is not None: from matplotlib.pyplot import title title(opts['title']) # Show grid ax.grid(opts['grid']) ax.minorticks_on() if opts['path'] is not None: from matplotlib.pyplot import savefig savefig(opts['path'] + '.' + opts['format']) if show: from matplotlib.pyplot import show as pltshow pltshow() return fig, ax
def singleplot(datax, datay, show=True, **kwargs): """ Plot multiple y-axis and possible multiple curves in each. Result is saved\ as a '.png' document. Parameters ---------- datax : list of numerics x-axis values. datay : list of lists of numerics y-axis values for each curves curve. labels : list, optional list of curve labels (the default is None). unitx : str, optional x-axis label (the default is None). unity : list of str, optional y-axis labels (the default is None). ylims : tuple of float, optional (ymin, ymax) values. If None then (ymin, ymax) is set automatically \ (the default is None). If extend the y-axis is extended by 5% on both sides (the default is \ 'extend'). linewidth : float, optional The default is 2. figsize : tuple of float, optional The default is (5., 5.). filelabel : str, optional Figure is saved in 'filelabel.png' (the default is 'multiplot'). loc : int or string or pair of floats, default: 0 The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= log : str, optional Log-scale activation according to =============== ============= Plot type Code =============== ============= 'plot' '' 'semilogx' 'x' 'semilogy' 'y' 'loglog' 'xy' =============== ============= linestyles : iterable, otpional List of line styles; the default is ('-b', '--r', ':g', '-.m'). fontsize : int, optional the default is figsize[0]*4. legendfontsize : int, optional Figure legend font size. If None then set to 4/5 of fontsize (the \ default is None). maintitle : str, optional Figure main title. If set to None, the desactivated (the default is \ None). axedef : tuple of floats, optional Figure geometry (left, botom, right, top). The default is (.15, .15, .85, .85). nbinsx, nbinsy : int, optional number of x-axis and y-axis ticks (the default is 4). minor : bool Activate the minor grid. markersize : float Default is 6. markeredgewidth : float Width of line around markers (the default is 0.5). """ opts = standard.copy() opts.update(kwargs) if opts['axedef'] is None: opts['axedef'] = [.15, .15, .75, .75] if opts['linestyles'] is None: opts['linestyles'] = ['-b', '--r', '-.g', ':m'] nplots = int(datay.__len__()) if opts['fontsize'] is None: opts['fontsize'] = int(4 * opts['figsize'][0]) if opts['legendfontsize'] is None: opts['legendfontsize'] = int(0.8 * opts['fontsize']) if opts['labels'] is None: opts['labels'] = [ None, ] * nplots if opts['log'] is None: opts['log'] = '' activate_latex(opts) from matplotlib.pyplot import rc rc('font', size=opts['fontsize'], **globalfonts()) from matplotlib.pyplot import close close('all') from matplotlib.pyplot import figure fig = figure(1, figsize=opts['figsize']) nplots = datay.__len__() if isinstance(datax[0], (float, int)): datax = [ datax, ] * nplots from matplotlib.pyplot import axes if opts['axedef'] is not None: geometry = opts['axedef'][:4] else: geometry = None ax = axes(geometry) miny = float('Inf') maxy = -float('Inf') for n in range(nplots): x = dec(datax[n], opts) y = dec(datay[n], opts) maxy = max([maxy, max(y)]) miny = min([miny, min(y)]) if isinstance(opts['labels'][n], (list, tuple)): annotate(x, y, opts['labels'][n][0], opts['labels'][n][1], opts['legendfontsize']) l = None else: l = opts['labels'][n] plotn = whichplot(opts['log'], ax) plotn(x, y, opts['linestyles'][n], linewidth=opts['linewidth'], markeredgewidth=opts['markeredgewidth'], markersize=opts['markersize'], label=l) setlims(ax, x, miny, maxy, opts['ylims']) setticks(ax, opts) from matplotlib.pyplot import legend legend(loc=opts['loc'], fontsize=opts['legendfontsize']) if opts['unitx'] is not None: from matplotlib.pyplot import xlabel xlabel(opts['unitx']) if opts['unity'] is not None: from matplotlib.pyplot import ylabel ylabel(opts['unity']) if opts['maintitle'] is not None: from matplotlib.pyplot import title title(opts['maintitle']) if opts['axedef'] is None: fig.tight_layout() if opts['filelabel'] is not None: from matplotlib.pyplot import savefig savefig(opts['filelabel'] + '.' + opts['format']) if show: from matplotlib.pyplot import show as pltshow pltshow()
def multiplot(x, y, show=True, **kwargs): """ Plot multiple y-axis and possible multiple curves in each. Result can be saved as a '.png' document. Parameters ---------- x : list of floats x-axis values. y : list of floats or of tuples of list of floats y-axis values per axis and per curve in each axis, if tuple. xlabel : str, optional x-axis label (the default is None). ylabels : list of str, optional y-axis label for each axe (the default is None). title : str, optional Figure main title. Desactivated if set to None (default). labels : list, optional list of curve labels (the default is None). Textboxes can be used with_files the elements syntax ['label', (xrel, yrel)] where xrel and yrel are relative x and y position. path : str, optional Figure is saved in 'path.ext' if provided (the default is None). Extension from pyphs config.py. loc : int or string or pair of floats, default: 0 The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= log : list of str, optional Log-scale activation for each axis according to =============== ============= Plot type Code =============== ============= 'plot' '' 'semilogx' 'x' 'semilogy' 'y' 'loglog' 'xy' =============== ============= linestyles : iterable, otpional List of line styles; the default is None. xpos_ylabel : float, optional If provided, set the x-position of the ylabels so that they align (the default is None). You probably want it to be negative. grid : bool Indicate whether to show the grid or not. """ # ------------------------------------------------------------ # Number of axes nplots = len(y) # ------------------------------------------------------------ # Recover standard options opts = standard.copy() # Update with new options opts.update(kwargs) # ------------------------------------------------------------ # Check fo options length if opts['ylabels'] is None: opts['ylabels'] = ['', ]*nplots elif not len(opts['ylabels']) == nplots: raise AttributeError('wrong number of y labels') if opts['labels'] is None: opts['labels'] = [None, ]*nplots elif not len(opts['ylabels']) == nplots: raise AttributeError('wrong number of curves labels') if opts['log'] is None: opts['log'] = ['', ] * nplots elif not len(opts['log']) == nplots: raise AttributeError('wrong number of log options') # ------------------------------------------------------------ # Init figure and axes from matplotlib.pyplot import subplots, fignum_exists i = 1 while fignum_exists(i): i += 1 fig, axs = subplots(nplots, 1, sharex=True, num=i) # ------------------------------------------------------------ # Iterate over y data for n, yn in enumerate(y): # -------------------------------------------------------- # get axe if nplots > 1: axe = axs[n] else: axe = axs axe.ticklabel_format(style='sci', scilimits=(-2, 2)) # -------------------------------------------------------- # flag print_legend = False # -------------------------------------------------------- # if yn is a list of values if (isinstance(yn[0], (float, int)) or (isinstance(yn[0], numpy.ndarray) and len(yn[0].shape) == 0)): # get plot in {plot, semilogx, semilogy, loglog} plotn = whichplot(opts['log'][n], axe) # Add label or annotation if isinstance(opts['labels'][n], (list, tuple)): annotate(*opts['labels'][n], ax=axe) l = None else: l = opts['labels'][n] print_legend = l is not None or print_legend # Plot if opts['linestyles'] is not None: plotn(x, yn, opts['linestyles'][n][0], label=l) else: plotn(x, yn, label=l) # -------------------------------------------------------- # if yn is a list of signals else: # get number of signals in yn len_yn = len(yn) # Set appropriate if opts['labels'][n] is None: opts['labels'][n] = (None, )*len_yn elif not len(opts['labels'][n]) == len_yn: raise AttributeError('wrong number of labels') # iterate over yn data for m, ynm in enumerate(yn): # Add label or annotation if isinstance(opts['labels'][n][m], (list, tuple)): annotate(*opts['labels'][n][m], ax=axe) l = None else: l = opts['labels'][n][m] print_legend = l is not None or print_legend # get plot in {plot, semilogx, semilogy, loglog} plotn = whichplot(opts['log'][n], axe) # Plot if opts['linestyles'] is not None: plotn(x, ynm, opts['linestyles'][n][m], label=l) else: plotn(x, ynm, label=l) # -------------------------------------------------------- # Print legend if print_legend: axs[n].legend(loc=opts['loc']) # -------------------------------------------------------- # Set y label if opts['ylabels'][n] is not None: axs[n].set_ylabel(opts['ylabels'][n]) if opts['xpos_ylabel'] is not None: axs[n].yaxis.set_label_coords(opts['xpos_ylabel'], 0.5) # -------------------------------------------------------- # Set x label if last plot if n == nplots-1: axs[n].set_xlabel(opts['xlabel']) else: from matplotlib.pyplot import setp setp(axs[n].get_xticklabels(), visible=False) # -------------------------------------------------------- # Show grid axs[n].grid(opts['grid']) axs[n].minorticks_on() # ------------------------------------------------------------ # Set title if opts['title'] is not None: from matplotlib.pyplot import suptitle suptitle(opts['title']) # ------------------------------------------------------------ # Save file if opts['path'] is not None: from matplotlib.pyplot import savefig savefig(opts['path'] + '.' + opts['format']) # ------------------------------------------------------------ # Show if show: from matplotlib.pyplot import show as pltshow pltshow() return fig, axs
def max_ocean(pl, n_stats=10, at_age=None, name_rms='dyn_top_aspect_prime', phi0=None, plot=False, verbose=False, spectrum_fname='base_spectrum_l1.pkl', spectrum_fpath='/home/claire/Works/exo-top/exotop/top_spectra/', rho_w=1000, **kwargs): water_load_ratio = pl.rho_m / (pl.rho_m - rho_w) if verbose: print('including water loading') if phi0 is None: degree, phi0 = sh.load_model_spectrum_pkl(fname=spectrum_fname, path=spectrum_fpath) h_rms1 = eval('pl.' + name_rms) if verbose: h_rms1_dim = eval('pl.' + 'dyn_top_rms') print('nondimensional h rms', h_rms1[-1]) print('dimensional h rms', h_rms1_dim[-1]) l = np.arange(len(phi0)) k = sh.l_to_k(l, R=2) # original model spectrum uses R_b = 2d = 2 h_rms0 = sh.parseval_rms(phi0, k) if np.isnan(h_rms0): print('phi0', phi0) print('k', k) raise Exception('rms of model spectrum is nan!') if at_age is not None: it = age_index(pl.t, at_age, parameters.sec2Gyr ) # get time index nearest to desired snap given in Gyr it = range(it, it + 1) else: # all times it = range(len(pl.t)) pl.max_ocean = np.zeros_like(it, dtype=np.float64) pl.h_peak_spectral = np.zeros_like(it, dtype=np.float64) for ii in it: h_rms = h_rms1[ii] h_ratio = h_rms / h_rms0 nn = 0 vols = [] peaks = [] rms_dims = [] rms_nondims = [] while nn < n_stats: clm = sh.random_harms_from_psd(phi0, l, R=2, h_ratio=h_ratio, plot=plot, verbose=verbose) # shgrid = sh.coeffs_to_grid(clm, R_b=2, plot_grid=False, plot_spectrum=False, verbose=verbose,) # lmax = shgrid.lmax # data = shgrid.data # lats = shgrid.lats() # lons = shgrid.lons() # vol = sh.integrate_to_peak(grid_dim, lats, lons, R_b=pl.R_p, lmax=shgrid.lmax, verbose=verbose) data = clm.expand(grid='GLQ', extend=False).to_array() lmax = clm.lmax rms_nondim = np.sqrt(np.mean(data**2)) # if verbose: # print('RMS of map nondimensional', rms_nondim) grid_dim = dimensionalise(data, pl, i=ii) * water_load_ratio vol = sh.integrate_to_peak_GLQ(grid_dim, R=pl.R_p, lmax=lmax, verbose=verbose) if np.isnan(vol): print('phi0', phi0, 'h_ratio', h_ratio) raise Exception('ocean vol nan!') vols.append(vol) rms_dim = np.sqrt(np.mean(grid_dim**2)) peaks.append(np.max(grid_dim)) rms_nondims.append(rms_nondim) rms_dims.append(rms_dim) nn = nn + 1 if verbose: # print('RMS of map dimensionalised', rms_dim, 'm') if nn > 0: verbose = False # don't repeat output basin_capacity = np.mean(vols) # phi = sh.scale_spectrum(h_rms=h_rms1[ii], **kwargs) # old verj # h_peak_grid = sh.hpeak_from_spectrum(phi, n=n_stats, **kwargs) # basin_capacity = sh.vol_from_peak(r0=pl.R_p, h_peak=h_peak_grid, **kwargs) if at_age is None: pl.max_ocean[ii] = basin_capacity pl.h_peak_spectral[ii] = np.mean(peaks) else: pl.max_ocean = basin_capacity pl.h_peak_spectral = np.mean(peaks) if verbose: print('\n') print(' scaled h_rms', name_rms, '=', dimensionalise(h_rms1[-1], pl=pl, i=-1), 'm without water loading') print(' water load ratio', water_load_ratio) print( "%.2f" % (pl.M_p / parameters.M_E), 'M_E |', "%.2f" % (pl.R_p * 1e-3), 'km radius | ocean vol:', "%.2f" % (basin_capacity / 1.4e18), 'EO | V_shell =', "%.2f" % (4 / 3 * np.pi * ((pl.R_p + np.mean(peaks))**3 - pl.R_p**3) / 1.4e18), 'EO | h_peak =', "%.2f" % (np.mean(peaks) * 1e-3), 'km | h_rms =', "%.2f" % (np.mean(rms_dims) * 1e-3), 'km') print('h_rms_prime =', "%.5f" % np.mean(rms_nondims), '| b =', "%.2f" % pl.b[-1], '| log Ra_i =', "%.2f" % np.log10(pl.Ra_i[-1]), '| d =', "%.2f" % (pl.d * 1e-3), '| dT =', "%.2f" % pl.delta_T[-1], '| alpha_m =', "%.2f" % pl.alpha_m) # print('t', ii, 'R_p:', pl.R_p * 1e-3, 'km, h_rms', h_rms1[ii]*1e-3, 'km, h_peak', h_spectrum_max * 1e-3, 'km, ocn vol:', basin_capacity / parameters.TO, 'TO') # print('final h_ratio', h_ratio) if plot: from matplotlib.pyplot import show as pltshow pltshow() return pl