def main():
    coverage_hist = pd.read_csv(ffile, sep='\t')
    globalreport = pd.Series(globaldepth(coverage_hist))
    globalreport = globalreport[[
        'mean_DP', 'median_DP', 'std_DP', 'q25_DP', 'q75_DP', 'q95_DP',
        'dp>=1', 'dp>=10', 'dp>=20', 'dp>=30', 'dp>=50', 'dp>=100'
    ]].to_frame()
    globalreport.columns = [sample]
    globalreport.to_csv(output_global_coverage, header=True, sep='\t')

    f = plt.figure(figsize=(14, 6))
    ax1 = f.add_subplot(121)
    ax2 = f.add_subplot(122)
    ax1.plot(coverage_hist.DP, coverage_hist.frequency)
    ax1.set_yscale('log')
    ax1.set_xscale('symlog')
    ax1.set_xlabel('DP')
    ax1.set_ylabel('density')
    ax1.xaxis.set_minor_locator(LogLocator(subs=np.arange(2, 10)))
    ax1.grid(True, which="both", ls="--")

    ax2.plot(coverage_hist.DP, coverage_hist['cumsum'].values, '.-')
    ax2.set_ylim((-0.02, 1))
    ax2.set_xscale('symlog')
    ax2.set_ylabel('Prob( bp > DP )')
    ax2.set_yticks(np.arange(0, 1., 0.1))
    ax2.set_xlabel('DP')
    ax2.xaxis.set_minor_locator(LogLocator(subs=np.arange(2, 10)))
    ax2.yaxis.set_minor_locator(AutoMinorLocator(2))
    ax2.grid(True, which="both", ls="--")
    f.savefig(out_plot, format='eps')
Esempio n. 2
0
def __decorate_axis(axis, ax_type):
    '''Configure axis tickers, locators, and labels'''

    if ax_type == 'tonnetz':
        axis.set_major_formatter(TONNETZ_FORMATTER)
        axis.set_major_locator(FixedLocator(0.5 + np.arange(6)))
        axis.set_label_text('Tonnetz')

    elif ax_type == 'chroma':
        axis.set_major_formatter(ChromaFormatter())
        axis.set_major_locator(FixedLocator(0.5 +
                                            np.add.outer(12 * np.arange(10),
                                                         [0, 2, 4, 5, 7, 9, 11]).ravel()))
        axis.set_label_text('Pitch class')

    elif ax_type == 'tempo':
        axis.set_major_formatter(ScalarFormatter())
        axis.set_major_locator(LogLocator(base=2.0))
        axis.set_label_text('BPM')

    elif ax_type == 'time':
        axis.set_major_formatter(TimeFormatter(lag=False))
        axis.set_major_locator(MaxNLocator(prune=None, steps=[1,5,10,15,20,30,45,60]))
        axis.set_label_text('Time')

    elif ax_type == 'lag':
        axis.set_major_formatter(TimeFormatter(lag=True))
        axis.set_major_locator(MaxNLocator(prune=None, steps=[1,5,10,15,20,30,45,60]))
        axis.set_label_text('Lag')

    elif ax_type == 'cqt_note':
        axis.set_major_formatter(NoteFormatter())
        axis.set_major_locator(LogLocator(base=2.0))
        axis.set_minor_formatter(NoteFormatter(major=False))
        axis.set_minor_locator(LogLocator(base=2.0,
                                          subs=2.0**(np.arange(1, 12)/12.0)))
        axis.set_label_text('Note')

    elif ax_type in ['cqt_hz']:
        axis.set_major_formatter(ScalarFormatter())
        axis.set_major_locator(LogLocator(base=2.0))
        axis.set_minor_locator(LogLocator(base=2.0,
                                          subs=2.0**(np.arange(1, 12)/12.0)))
        axis.set_label_text('Hz')

    elif ax_type in ['mel', 'log']:
        axis.set_major_formatter(ScalarFormatter())
        axis.set_major_locator(SymmetricalLogLocator(axis.get_transform()))
        axis.set_label_text('Hz')

    elif ax_type in ['linear', 'hz']:
        axis.set_major_formatter(ScalarFormatter())
        axis.set_label_text('Hz')

    elif ax_type in ['frames']:
        axis.set_label_text('Frames')

    elif ax_type in ['off', 'none', None]:
        axis.set_label_text('')
        axis.set_ticks([])
Esempio n. 3
0
def plot_timings(timings,
                 title=None,
                 figure=None,
                 seaborn_style: Optional[dict] = DEFAULT_SEABORN_STYLE):
    if seaborn_style is not None:
        import seaborn
        seaborn.set(**seaborn_style)
    from matplotlib.ticker import LogLocator, LogFormatter
    if figure is None:
        import matplotlib.pyplot as plt
        figure: plt.Figure = plt.figure(figsize=(9, 4))
    axes = figure.gca(xlabel='n_features', ylabel='time[s]')
    if title is not None:
        axes.set_title(title)

    timings = np.asarray(timings)
    # sort by n_features so plot lines make sense
    timings = timings[np.argsort(timings[:, 1])]

    n_samples = timings.T[0]
    n_features = timings.T[1]
    tm_min = timings.T[2]
    for n in np.unique(n_samples)[::-1]:  # reverse so legend is in order
        mask = n_samples == n
        axes.loglog(n_features[mask], tm_min[mask], '.-', label=str(int(n)))
    axes.legend(title='n_samples', ncol=1, handlelength=0)
    axes.grid(True, which='both', axis='both')
    figure.tight_layout()
    # show more ticks
    axes.xaxis.set_major_locator(LogLocator(subs='all'))
    axes.xaxis.set_major_formatter(LogFormatter(minor_thresholds=(100, 0.4)))
    axes.yaxis.set_major_locator(LogLocator(subs='all'))
    return figure
Esempio n. 4
0
def update_colorbar_scale(figure, image, scale, vmin, vmax):
    """"
    Updates the colorbar to the scale and limits given.

    :param figure: A matplotlib figure instance
    :param image: The matplotlib image containing the colorbar
    :param scale: The norm scale of the colorbar, this should be a matplotlib colormap norm type
    :param vmin: the minimum value on the colorbar
    :param vmax: the maximum value on the colorbar
    """
    if vmin <= 0 and scale == LogNorm:
        vmin = 0.0001  # Avoid 0 log scale error
        mantid.kernel.logger.warning(
            "Scale is set to logarithmic so non-positive min value has been changed to 0.0001."
        )

    if vmax <= 0 and scale == LogNorm:
        vmax = 1  # Avoid 0 log scale error
        mantid.kernel.logger.warning(
            "Scale is set to logarithmic so non-positive max value has been changed to 1."
        )

    image.set_norm(scale(vmin=vmin, vmax=vmax))
    if image.colorbar:
        image.colorbar.remove()
        locator = None
        if scale == LogNorm:
            locator = LogLocator(subs=np.arange(1, 10))
            if locator.tick_values(vmin=vmin, vmax=vmax).size == 0:
                locator = LogLocator()
                mantid.kernel.logger.warning(
                    "Minor ticks on colorbar scale cannot be shown "
                    "as the range between min value and max value is too large"
                )
        figure.colorbar(image, ticks=locator)
Esempio n. 5
0
    def colorbar(self, clev):
        """"""

        cb = plt.colorbar(clev, orientation='horizontal', extend='both', pad=.1, format=self.cb_fmt)

        # Adjust colorbar ticks for log scale
        if isinstance(clev.norm, (LogNorm, SymLogNorm)):
            clim = list(clev.get_clim())

            # For symmetric log scales, the central tick is the linear threshold
            if self.pm:
                clim[0] = clev.norm.linthresh

            # Determine major (every decade) and minor (every tenth of a decade) ticks
            minor_ticks = LogLocator(subs=range(2, 10)).tick_values(*clim)
            major_ticks = LogLocator().tick_values(*clim)
            minor_ticks = minor_ticks[(clim[0] <= minor_ticks) & (clim[1] >= minor_ticks)]
            major_ticks = major_ticks[(clim[0] <= major_ticks) & (clim[1] >= major_ticks)]

            # For symmetric log scales, ticks are mirrored around the central tick
            if self.pm:
                minor_ticks = np.concatenate([-minor_ticks, minor_ticks])
                major_ticks = np.concatenate([-major_ticks[1:], major_ticks])

            cb.set_ticks(major_ticks)

            # TODO: When self.cb_fmt = None, this drops the offset label (no longer a ScalarFormatter)- need to add
            # it back manually or use a FuncFormatter For symmetric log scales, update the central tick label to
            # indicate that it represents the linear threshold
            if self.pm:
                major_ticklabels = [i.get_text() for i in cb.ax.xaxis.get_ticklabels()]
                major_ticklabels[len(major_ticks) / 2] = '< |{}|'.format(major_ticklabels[len(major_ticks) / 2])
                cb.set_ticklabels(major_ticklabels)

            cb.ax.xaxis.set_ticks(clev.norm(minor_ticks), minor=True)
Esempio n. 6
0
    def _polish(self, f):
        # Handle properties of axes directly
        #a = plt.gca() # Current set of axes
        formatter_scalar = ScalarFormatter(useOffset=True, useMathText=False)
        formatter_scalar.set_powerlimits((-3, 3))
        formatter_log = LogFormatterMathtext(base=10.0, labelOnlyBase=False)

        # Neaten axes formatters
        for ax in f.get_axes():

            if not isinstance(ax.xaxis.get_major_formatter(), NullFormatter):
                if ax.xaxis.get_scale() == "log":
                    ax.xaxis.set_major_locator(
                        LogLocator(base=10.0, subs=[1.0], numdecs=1))
                    ax.xaxis.set_major_formatter(formatter_log)
                else:
                    ax.xaxis.set_major_formatter(formatter_scalar)
            if not isinstance(ax.yaxis.get_major_formatter(), NullFormatter):
                if ax.yaxis.get_scale() == "log":
                    ax.yaxis.set_major_locator(
                        LogLocator(base=10.0, subs=[1.0], numdecs=1))
                    ax.yaxis.set_major_formatter(formatter_log)
                    #ax.yaxis.set_minor_locator(LogLocator(base=10.0, subs=[10], numdecs=1)) # why is this necessary?
                else:
                    ax.yaxis.set_major_formatter(formatter_scalar)
Esempio n. 7
0
 def set_default_locators_and_formatters(self, axis):
     # docstring inherited
     axis.set_major_locator(LogLocator(self.base))
     axis.set_major_formatter(LogFormatterSciNotation(self.base))
     axis.set_minor_locator(LogLocator(self.base, self.subs))
     axis.set_minor_formatter(
         LogFormatterSciNotation(self.base,
                                 labelOnlyBase=(self.subs is not None)))
Esempio n. 8
0
 def set_default_locators_and_formatters(self, axis):
     if isinstance(axis, XAxis):
         axis.set_tick_params(which='both', pad=7)
         axis.labelpad = 8
     axis.set_major_locator(LogLocator(self.base))
     axis.set_major_formatter(GWpyLogFormatterMathtext(self.base))
     axis.set_minor_locator(LogLocator(self.base, self.subs))
     axis.set_minor_formatter(MinorLogFormatterMathtext(self.base))
Esempio n. 9
0
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to specialized versions for
     log scaling.
     """
     axis.set_major_locator(LogLocator(self.base))
     axis.set_major_formatter(LogFormatterMathtext(self.base))
     axis.set_minor_locator(LogLocator(self.base, self.subs))
     axis.set_minor_formatter(NullFormatter())
Esempio n. 10
0
def visualize_periodic():
    f = h5py.File('periodic_output.hdf5', 'r',
                  driver='mpio', comm=mpi4py.MPI.COMM_WORLD)
    iterations = f.get("its")[:]
    dofs = f.get("num_dofs")[:]
    slaves = np.sum(f.get("num_slaves")[:], axis=1)

    solver = f.get("solve_time").attrs["solver"].decode("utf-8")
    ct = f.get("solve_time").attrs["ct"].decode("utf-8")
    degree = f.get("solve_time").attrs["degree"].decode("utf-8")
    f.close()

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    plt.plot(dofs, iterations, "-ro", label="MPC", markersize=12)

    f_ref = h5py.File('periodic_ref_output.hdf5', 'r',
                      driver='mpio', comm=mpi4py.MPI.COMM_WORLD)
    iterations_ref = f_ref.get("its")[:]
    dofs_ref = f_ref.get("num_dofs")[:]
    f_ref.close()

    plt.plot(dofs_ref, iterations_ref, "-bs", label="Unconstrained")

    ax.tick_params(axis='both', which='major', labelsize=20)
    ax.set_xscale("log")
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax.set_ylim([0, max(iterations) + 1])
    ax.set_xlim([1e2, max(dofs) + 1])
    plt.xlabel("# DOFS", fontsize=20)
    plt.ylabel("# Iterations", fontsize=20)

    trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
                                           x=0.025, y=0.025, units='inches')
    for i in range(len(iterations)):
        plt.text(dofs[i], iterations[i], slaves[i],
                 transform=trans_offset, fontsize=20)
    plt.title("Periodic Poisson (CG {0:s}, {1:s}) with {2:s}".format(
        degree, ct, solver), fontsize=25)
    plt.legend(fontsize=15)
    ax.minorticks_on()
    ax.set_ylim([0, max(iterations) + 1])
    ax.set_xlim([1e2, 1e8])
    locmax = LogLocator(
        base=10.0,
        numticks=8)
    ax.xaxis.set_major_locator(locmax)
    locmin = LogLocator(
        base=10.0, subs=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9),
        numticks=9)
    ax.xaxis.set_minor_locator(locmin)
    ax.xaxis.set_minor_formatter(NullFormatter())
    plt.grid(True, which="both", axis="both")
    plt.savefig("periodic_iterations_CG{0:s}_{1:s}.png".format(
        degree, ct), bbox_inches='tight')
Esempio n. 11
0
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to specialized versions for
     log scaling.
     """
     axis.set_major_locator(LogLocator(self.base))
     axis.set_major_formatter(LogFormatterSciNotation(self.base))
     axis.set_minor_locator(LogLocator(self.base, self.subs))
     axis.set_minor_formatter(
         LogFormatterSciNotation(self.base, labelOnlyBase=self.subs))
Esempio n. 12
0
    def _get_locators(self, locator, at, upto, count, every, between, minor):

        log_base, symlog_thresh = self._parse_for_log_params(self.trans)

        if locator is not None:
            major_locator = locator

        elif upto is not None:
            if log_base:
                major_locator = LogLocator(base=log_base, numticks=upto)
            else:
                major_locator = MaxNLocator(upto, steps=[1, 1.5, 2, 2.5, 3, 5, 10])

        elif count is not None:
            if between is None:
                # This is rarely useful (unless you are setting limits)
                major_locator = LinearLocator(count)
            else:
                if log_base or symlog_thresh:
                    forward, inverse = self._get_transform()
                    lo, hi = forward(between)
                    ticks = inverse(np.linspace(lo, hi, num=count))
                else:
                    ticks = np.linspace(*between, num=count)
                major_locator = FixedLocator(ticks)

        elif every is not None:
            if between is None:
                major_locator = MultipleLocator(every)
            else:
                lo, hi = between
                ticks = np.arange(lo, hi + every, every)
                major_locator = FixedLocator(ticks)

        elif at is not None:
            major_locator = FixedLocator(at)

        else:
            if log_base:
                major_locator = LogLocator(log_base)
            elif symlog_thresh:
                major_locator = SymmetricalLogLocator(linthresh=symlog_thresh, base=10)
            else:
                major_locator = AutoLocator()

        if minor is None:
            minor_locator = LogLocator(log_base, subs=None) if log_base else None
        else:
            if log_base:
                subs = np.linspace(0, log_base, minor + 2)[1:-1]
                minor_locator = LogLocator(log_base, subs=subs)
            else:
                minor_locator = AutoMinorLocator(minor + 1)

        return major_locator, minor_locator
Esempio n. 13
0
def build_chart(x_data, y_data, label_req, dur, scatter = False ):   
    matplotlib.rcParams.update({'font.family': 'monospace'})
    label = labels[label_req]
    
    dates = mdate.epoch2num(x_data)
    fig, ax = plt.subplots()
    
    if scatter:
        plt.scatter(dates, y_data,s=.01)
    else:
        ax.plot(dates, y_data,linewidth=.5,color = 'black')
        
    if dur !='1M':
        label['x-axis'] ='Year'
        
    if label['scale']:
        if 'ℳ' in list(label['y-axis']) :
            plt.ylabel('ℳ', fontdict = {'family': 'sans'})
        ax.set(xlabel = label['x-axis'], ylabel = label['y-axis'], title = label['title'], yscale = label['scale'])
    else:
        ax.set(xlabel = label['x-axis'], ylabel = label['y-axis'], title = label['title'])

    
    if label['scale']=='log':
        ax.yaxis.set_major_locator(LogLocator(base=10))
        ax.yaxis.set_minor_locator(LogLocator(base=10,subs=[0.0, 0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]))
        ax.yaxis.set_major_formatter(LogFormatterMathtext(labelOnlyBase=True))
    
    if dur == '1M':
        date_formatter = mdate.DateFormatter('%m/%d/%y')
        ax.xaxis.set_minor_locator(mdate.DayLocator())
        ax.xaxis.set_major_locator(mdate.WeekdayLocator(byweekday = mdate.SU))
        ax.xaxis.set_major_formatter(date_formatter)
    elif dur == '1Y':
        date_formatter = mdate.DateFormatter("%b.%y")
        ax.xaxis.set_minor_locator(mdate.MonthLocator())
        ax.xaxis.set_major_locator(mdate.MonthLocator(bymonth=[1,4,7,10]))
        ax.xaxis.set_major_formatter(date_formatter)
    else:
        date_formatter = mdate.DateFormatter('%y')
        ax.xaxis.set_minor_locator(mdate.MonthLocator(bymonth=[1,4,7,10]))
        ax.xaxis.set_major_locator(mdate.YearLocator())
        ax.xaxis.set_major_formatter(date_formatter)
        
    
    ax.grid(which='major',linestyle = '--')
    ax.grid(which='minor',linestyle = ':')
    ax.grid(True)
    
    fig.set_size_inches(8,5)
    fig.savefig("static/data/"+ label['file-name'] +"_" + dur + ".png",dpi=150)
    plt.cla() 
    plt.clf() 
    plt.close('all')
    return True
Esempio n. 14
0
def addAEPGrid(axes):
    """
    Add a logarithmic graticuyle to the subplot axes
    :param axes: :class:`axes` instance
    """
    axes.yaxis.set_major_locator(LogLocator())
    axes.yaxis.set_minor_locator(
        LogLocator(subs=[.1, .2, .3, .4, .5, .6, .7, .8, .9]))
    axes.autoscale(True, axis='y', tight=True)
    axes.grid(True, which='major', linestyle='-')
    axes.grid(True, which='minor', linestyle='--', linewidth=0.5)
Esempio n. 15
0
def format_log_axis(ax, num_ticks):
    """
    change ax tick to 1, 10, 100, 1000, ...
    add proper minor ticks
    """
    ax.set_major_locator(LogLocator(base=10, numticks=num_ticks))
    ax.set_minor_locator(
        LogLocator(base=10,
                   subs=(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9),
                   numticks=num_ticks), )
    ax.set_minor_formatter(NullFormatter())
Esempio n. 16
0
def make_single_plots(qArray, quantity, layerOverlap, hitOverlap,
                      layer_binary):
    minValue = min(qArray[qArray > -999])
    maxValue = max(qArray)
    histMinLimit = 9e-6
    histMaxLimit = 1.1e2
    if abs(histMaxLimit -
           histMinLimit) > 10 and histMinLimit > 0 or "/" in quantity:
        binning = np.logspace(np.log10(histMinLimit), np.log10(histMaxLimit),
                              500)
    else:
        binning = np.linspace(histMinLimit, histMaxLimit, 500)

    allHist = Hist1D(ak.to_numpy(qArray[qArray > -999]),
                     bins=binning,
                     label="{}".format(quantity))
    fig, ax = plt.subplots()
    ax.set_yscale("log")
    if abs(histMaxLimit -
           histMinLimit) > 10 and histMinLimit > 0 or "/" in quantity:
        x_major = LogLocator(base=10.0, numticks=5)
        x_minor = LogLocator(base=10.0,
                             subs=np.arange(1.0, 10.0) * 0.1,
                             numticks=10)
        ax.xaxis.set_major_locator(x_major)
        ax.xaxis.set_minor_locator(x_minor)
        ax.xaxis.set_minor_formatter(NullFormatter())
        ax.set_xscale("log")

    #find the 99%

    print("99% limit at {}".format(allHist.quantile(0.99)))

    allHist.plot(alpha=0.8, color="C0", label="all", histtype="stepfilled")

    layers = parseLayers(layer_binary)
    plt.title("{}, layer overlap = {}, hit overlap = {}".format(
        (",").join(layers), layerOverlap, hitOverlap))
    plt.xlabel(quantity)

    plt.suptitle("Sample = {}".format(sys.argv[3]))

    if "inner" in quantity:
        plt.savefig(
            "{}/inner_v_sim_layerOverlap_{}_hitOverlap_{}_{}.pdf".format(
                sys.argv[2], layerOverlap, hitOverlap, ("").join(layers)))
    else:
        plt.savefig(
            "{}/outer_v_sim_layerOverlap_{}_hitOverlap_{}_{}.pdf".format(
                sys.argv[2], layerOverlap, hitOverlap, ("").join(layers)))

    plt.close()
Esempio n. 17
0
    def addGrid(self, axes):
        """
        Add a logarithmic graticule to the subplot axes.

        :param axes: :class:`axes` instance.

        """

        axes.xaxis.set_major_locator(LogLocator())
        axes.xaxis.set_major_formatter(FormatStrFormatter('%d'))
        axes.xaxis.set_minor_locator(LogLocator(subs=[.1, .2, .3, .4, .5, .6, .7, .8, .9]))
        axes.autoscale(True, axis='x', tight=True)
        axes.grid(True, which='major', linestyle='-', linewidth=0.5)
        axes.grid(True, which='minor', linestyle='-', linewidth=0.5)
Esempio n. 18
0
def plot_window_function_2d(path_window,key,scale='slinlin',title='$\\mathcal{W}_{\ell}(s)$',path='window_2d.png'):
	
	window = WindowFunction.load(path_window)
	s,d = window.s[0][window.s[0]>0.],window.s[1][window.s[1]>0.]
	#s,d = window.s[0][window.s[0]>0.],window.s[1][window.s[1]>1.e3]
	scaling = scalings[scale]
	s = s[(s>=scaling['xlim'][0]) & (s<scaling['xlim'][-1])]
	d = d[(d>=scaling['xlim'][0]) & (d<scaling['xlim'][-1])]
	figsize = 7; xextend = 0.8
	xlabel,ylabel = ('$s$ [$\\mathrm{Mpc} \ h^{-1}$]','$\\Delta$ [$\\mathrm{Mpc} \ h^{-1}$]')
	cmap = pyplot.get_cmap('Spectral')
	ells1,ells2 = window.ells
	#ells1,ells2 = ells1[:3],ells2[:3]
	ells1,ells2 = [2],[0]
	tmp = [window((s,d),(ell1,ell2)) for ell1 in ells1 for ell2 in ells2]
	norm = Normalize(scipy.amin(tmp),scipy.amax(tmp))
	#norm = Normalize(0,1)
	ncols = len(ells1); nrows = len(ells2)
	fig = pyplot.figure(figsize=(figsize/xextend,figsize))
	if title is not None: fig.suptitle(title,fontsize=fontsize)
	gs = gridspec.GridSpec(nrows,ncols,wspace=0.1,hspace=0.1)
	for ill1,ell1 in enumerate(ells1):
		for ill2,ell2 in enumerate(ells2):
			ax = pyplot.subplot(gs[nrows-1-ill2,ill1])
			im = ax.pcolormesh(s,d,window([s,d],(ell1,ell2)).T,norm=norm,cmap=cmap)
			#im = ax.pcolormesh(s,d,scipy.log(scipy.absolute(window([s,d],(ell1,ell2)).T)),norm=norm,cmap=cmap)
			ax.set_xscale(scaling['xscale'])
			ax.set_yscale(scaling['xscale'])
			if ill1>0: ax.get_yaxis().set_visible(False)
			elif 'log' in scale:
				ax.yaxis.set_major_locator(LogLocator(base=10.,subs=(1,),numticks=3))
				ax.yaxis.set_minor_locator(LogLocator(base=10.,subs=range(1,11),numticks=3))
				ax.yaxis.set_minor_formatter(NullFormatter())
			if ill2>0: ax.get_xaxis().set_visible(False)
			elif 'log' in scale:
				ax.xaxis.set_major_locator(LogLocator(base=10.,subs=(1,),numticks=3))
				ax.xaxis.set_minor_locator(LogLocator(base=10.,subs=range(1,11),numticks=3))
				ax.xaxis.set_minor_formatter(NullFormatter())
			ax.tick_params(labelsize=labelsize)
			text = '$\\mathcal{{W}}_{{{:d},{:d}}}$'.format(ell1,ell2)
			ax.text(0.05,0.95,text,horizontalalignment='left',verticalalignment='top',transform=ax.transAxes,color='black',fontsize=labelsize)
	utils.suplabel('x',xlabel,shift=-0.04,labelpad=7,size=labelsize)
	utils.suplabel('y',ylabel,shift=0,labelpad=8,size=labelsize)
	fig.subplots_adjust(right=xextend)
	cbar_ax = fig.add_axes([xextend+0.05,0.15,0.03,0.7])
	cbar_ax.tick_params(labelsize=labelsize)
	cbar = fig.colorbar(im,cax=cbar_ax,format='%.1e')

	utils.savefig(path,dpi=dpi,bbox_inches='tight',pad_inches=0.1)
Esempio n. 19
0
def setup(ax, indx, num_cc, point_boundary):
    data_tail = [[], []]
    data_tail_targets = [[], []]
    data_targets = [[], []]

    for line in open(indx + '_tail'):
        data = line.split()
        data_tail[0].append(float(data[0]))
        data_tail[1].append(float(data[1]))

    for line in open(indx + '_tail_other_targets'):
        data = line.split()
        data_tail_targets[0].append(float(data[0]))
        data_tail_targets[1].append(float(data[1]))

    for line in open(indx + '_other_targets'):
        data = line.split()
        data_targets[0].append(float(data[0]))
        data_targets[1].append(float(data[1]))

    ax.semilogy(data_tail[0][:point_boundary],
                data_tail[1][:point_boundary],
                'b',
                label=str(num_cc) + 'CC BPRM')
    ax.semilogy(data_tail[0][point_boundary:],
                data_tail[1][point_boundary:],
                '-.g',
                label='Tail')

    ax.semilogy(data_targets[0], data_targets[1], 'k', label='Other cores')

    ax.semilogy(data_tail_targets[0],
                data_tail_targets[1],
                'r',
                label='Total (including other cores)')

    ax.legend(prop={'size': 8})
    ax.set_xlim(0, 530)

    ax.yaxis.set_major_locator(LogLocator(base=10, numticks=6))
    ax.set_yticklabels(ax.get_yticks())
    labels = [
        str(int(log10(float(label.get_text()))))
        for label in ax.get_yticklabels()
    ]
    ax.set_yticklabels(labels)
    ax.yaxis.set_minor_locator(
        LogLocator(base=10, subs=(0.2, 0, 4, 0.6, 0.8), numticks=24))
    ax.xaxis.set_minor_locator(AutoMinorLocator(5))
Esempio n. 20
0
def set_log_chart_params(ax):
    for a in np.ndindex(ax.shape):
        ax[a].set_yscale('log')
        ax[a].set_xlabel('Pipe Diameter (in)')
        ax[a].set_ylabel('Cost ($)')
        ax[a].legend()
        # x ticks
        ax[a].xaxis.set_major_locator(MultipleLocator(4))
        ax[a].xaxis.set_minor_locator(MultipleLocator(2))
        ax[a].yaxis.set_major_locator(LogLocator(base=10))
        subs = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)
        locmin = LogLocator(base=10.0, subs=subs, numticks=12)
        ax[a].yaxis.set_minor_locator(locmin)
        ax[a].grid(which='minor', color='#f0f0f0', zorder=0)
        ax[a].grid(which='major', color='#ccc', zorder=0)
Esempio n. 21
0
def PlotFlowRateVsTime(Data):
    fig = plt.figure(figsize=(10, 7))
    ax = fig.gca()
    plt.xlabel('Time [Hours]', fontsize=16)
    plt.ylabel(r'Outgassing Rate [mBar$\,\cdot\,$Liter/s]', fontsize=16)
    plt.yscale('log')
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    ax.grid(b=True, which='major', color='grey', linestyle='--')
    ax.grid(b=True, which='minor', color='grey', linestyle=':')
    ax.xaxis.set_minor_locator(AutoMinorLocator(5))
    ax.xaxis.set_major_locator(MultipleLocator(10))
    ax.yaxis.set_major_locator(LogLocator(
        base=10,
        numticks=12,
    ))
    for jj, data in enumerate(Data):
        for ii, (X, Y) in enumerate(zip(data.Time, data.FlowRate)):
            plt.plot(X,
                     Y,
                     label=data.Labels[ii],
                     color=colors[jj],
                     linewidth=2.)

    plt.xlim(np.min(Data[0].Time[0]), np.max(Data[0].Time[-1]))
    plt.ylim(ymin=1E-12)
    ax.legend(loc='upper right', fontsize=14)
    fig.tight_layout()
Esempio n. 22
0
def plot_variable(filename,
                  varname,
                  rmin=0,
                  log=None,
                  plot_fit=None,
                  p0=[-1, -1, 20]):

    var = ExoReader(filename).read(varname)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlabel(var.r_label, labelpad=10, fontsize=20)
    ax.set_ylabel(var.label, labelpad=10, fontsize=20)
    ax.tick_params(labelsize=20)

    r_data = var.r[var.r >= rmin]
    var_data = var.data[var.r >= rmin]

    ax.set_xlim(rmin, max(r_data))

    if not not plot_fit:
        r_data /= r_data[0]
        var_data /= var_data[0]
        ax.set_xlim(1, max(r_data))
    ax.plot(r_data, var_data, "x")

    if not not plot_fit:
        fpars = fit_variable(filename,
                             varname,
                             algorithm=plot_fit,
                             rmin=rmin,
                             p0=p0)
        p = fpars[2]
        cov = fpars[3]
        if plot_fit == "power":
            y_data = fit_powerlaw(r_data, p[0])
        elif plot_fit == "curved":
            y_data = fit_curved_powerlaw(r_data, p[0], p[1])
        elif plot_fit == "double":
            y_data = fit_double_powerlaw(r_data, p[0], p[1])
        elif plot_fit == "broken":
            y_data = fit_broken_powerlaw(r_data, p[0], p[1], p[2])
        elif plot_fit == "exp":
            y_data = fit_exp_powerlaw(r_data, p[0], p[1])
        ax.plot(r_data, y_data, color="r")

    if not not log:
        plt.yscale("log")
        ax.yaxis.set_major_locator(LogLocator())

    ax.xaxis.set_major_locator(AutoLocator())
    if not log:
        ax.yaxis.set_major_locator(AutoLocator())

    plt.tight_layout()
    plt.grid(which="major")
    plt.grid(which="minor")
    plt.show()

    return [p, cov]
Esempio n. 23
0
def fitAndPlotLinear(x, y, rngt, ax, alfa, showPlot, labelAlfa, p):
    markers=["o", "s","D","^","d","h","p","o"]
    labelRange = ['low', 'med', 'high']
    labelRange = labelRange+list([str(i) for i in rngt])
    cm = plt.get_cmap('Set1')
    cm1 = plt.get_cmap('Set3')
    slopes = []
    if showPlot:
        inf.smallerFont(ax, 8)
        ax.scatter(x, y, color=cm(abs(alfa/9)), alpha=0.75, edgecolors='none', marker=markers[alfa])#, "o", lw=0.5)
        arrow = dict(arrowstyle="-", connectionstyle="arc3", ls="--", color="gray")
        putLabels(ax, p.calc, alfa)
    for i in range(0,len(rngt)-1):
        a, b = fun.linearFit(x, y, rngt[i], rngt[i+1])
        slopes.append(b)
        if showPlot:
            ax.semilogy(x[rngt[i]:rngt[i+1]+1], np.exp(fun.linear(x[rngt[i]:rngt[i+1]+1], a, b)), ls="-", color=cm1((i+abs(alfa)*3)/12))
            xHalf = (x[rngt[i]]+x[rngt[i+1]]+1)/2
            text = "{:03.3f}".format(-b)
            yHalf = np.exp(fun.linear(xHalf, a, b))
            if alfa == -1:
                ax.text(xHalf, 2e1, r"$"+roman.toRoman(i+1)+r"$", color="gray", ha="right", va="center")#, transform=axarr[i].transAxes)
                xHalf *= 1.15
                yHalf *= 5
                text = r"$E_a="+text+r"$"

            bbox_props = dict(boxstyle="round", fc="w", ec="1", alpha=0.6)
            ax.text(xHalf,yHalf, text, color=cm(abs(alfa/9)), bbox=bbox_props, ha="center", va="center", size=6)
    if showPlot and alfa > -1:
        locator = LogLocator(100,[1e-1])
        ax.yaxis.set_major_locator(locator)
    return slopes
Esempio n. 24
0
def PlotImpuritiesVsTime(Data):
    fig = plt.figure(figsize=(10, 7))
    ax = fig.gca()
    plt.xlabel('Time [hours]', fontsize=16)
    plt.ylabel(r'Total Number of Impurities', fontsize=16)
    plt.yscale('log')
    plt.xticks(fontsize=16)
    plt.yticks(fontsize=16)
    ax.grid(b=True, which='major', color='grey', linestyle='--')
    ax.grid(b=True, which='minor', color='grey', linestyle=':')
    ax.xaxis.set_minor_locator(AutoMinorLocator(5))
    ax.xaxis.set_major_locator(MultipleLocator(10))
    ax.yaxis.set_major_locator(LogLocator(
        base=10,
        numticks=12,
    ))
    for jj, data in enumerate(Data):
        for ii, (X, Y) in enumerate(zip(data.Time, data.Impurities)):
            plt.plot(X,
                     Y,
                     label=data.Labels[ii],
                     color=colors[jj],
                     linewidth=2.)

    plt.xlim(np.min(Data[0].Time[0]), np.max(Data[0].Time[-1]))
    # plt.ylim(ymin=1E12,ymax=1E20)
    ax.legend(loc='upper right', fontsize=14)
    fig.tight_layout()
Esempio n. 25
0
def establishTicks(axMain, axCrazy, axBlowUp, options, data):
    #data.axDict['main'].set_xticks( data.xData )
    #data.axDict['main'].set_xticklabels( prettyList( data.valuesDict['columnLength'] ))
    if options.mode in set(
        ['blocks', 'contigs', 'contigPaths', 'scaffPaths', 'scaffolds']):
        if not options.SMM:
            if options.mode != 'contigPaths' and options.mode != 'scaffPaths':
                axCrazy.set_yticks([0, 1])
                axCrazy.set_yticklabels([0, '%d' % data.crazyMax])
    minorLocator = MultipleLocator(5)
    minorLocator = LogLocator(base=10, subs=range(1, 10))

    if options.SMM:
        axBlowUp.set_yticklabels([])
        axBlowUp.set_xticklabels([])
        axMain.set_yticklabels([])
        axMain.set_xticklabels([])
        for i in xrange(1, 8):
            axMain.add_line(
                lines.Line2D(xdata=[10**i, 10**i],
                             ydata=[0, 0.1],
                             color=(0.8, 0.8, 0.8),
                             linewidth=0.5))
    else:
        axBlowUp.set_yticks([0.9, 0.92, 0.94, 0.96, 0.98, 1.0], minor=False)
        axBlowUp.set_yticks(
            [0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1.0],
            minor=True)
        axMain.xaxis.set_minor_locator(minorLocator)
        axBlowUp.xaxis.set_minor_locator(minorLocator)
        if axCrazy:
            axCrazy.xaxis.set_minor_locator(minorLocator)
Esempio n. 26
0
def plot_prpl_ratio(interp_pkl_num, interp_pkl_den, include_cbar=True):
    emui_edges, l_ice_edges, prpls_num = plot_prpl(interp_pkl_num, False,
                                                   False)
    emui_edges, l_ice_edges, prpls_den = plot_prpl(interp_pkl_den, False,
                                                   False)
    plt.figure()
    plt.pcolormesh(emui_edges,
                   l_ice_edges / 1e3,
                   np.ma.masked_invalid(prpls_num / prpls_den),
                   norm=colors.LogNorm(vmin=1e-2, vmax=1e2),
                   cmap='coolwarm')
    if include_cbar:
        plt.colorbar()
    plt.xlabel(r'$E_\mu^{\rm i}$ [GeV]')
    plt.ylabel(r'$l_{\rm ice}$ [km]')
    # plt.yscale('log')
    # plt.gca().yaxis.set_major_formatter(ScalarFormatter())
    plt.xscale('log')
    xlocmaj = LogLocator(base=10, numticks=12)
    plt.gca().xaxis.set_major_locator(xlocmaj)
    plt.gca().minorticks_off()
    plt.ticklabel_format(style='plain', axis='y')
    plt.xlim(1e2, 1e8)
    plt.ylim(1, 40)
    plt.title('{}/{}'.format(
        os.path.splitext(os.path.basename(interp_pkl_num))[0],
        os.path.splitext(os.path.basename(interp_pkl_den))[0]))
Esempio n. 27
0
File: log.py Progetto: sdurve/sfepy
    def process_command(self, command):
        from matplotlib.ticker import LogLocator, AutoLocator

        self.output(command[0])

        if command[0] == 'ig':
            self.ig = command[1]

        elif command[0] == 'plot':
            xdata, ydata = command[1:]

            ig = self.ig
            ax = self.ax[ig]
            ax.set_yscale(self.yscales[ig])
            ax.yaxis.grid(True)
            ax.plot(xdata, ydata)

            if self.yscales[ig] == 'log':
                ymajor_formatter = ax.yaxis.get_major_formatter()
                ymajor_formatter.label_minor(True)
                yminor_locator = LogLocator()
            else:
                yminor_locator = AutoLocator()
                self.ax[ig].yaxis.set_minor_locator(yminor_locator)

        elif command[0] == 'vline':
            x, kwargs = command[1:]

            self.vlines[self.ig].append((x, kwargs))

        elif command[0] == 'clear':
            self.ax[self.ig].cla()

        elif command[0] == 'legends':
            for ig, ax in enumerate(self.ax):
                try:
                    ax.legend(self.data_names[ig])
                except:
                    pass

                if self.xlabels[ig]:
                    ax.set_xlabel(self.xlabels[ig])
                if self.ylabels[ig]:
                    ax.set_ylabel(self.ylabels[ig])

                for x, kwargs in self.vlines[ig]:
                    ax.axvline(x, **kwargs)

        elif command[0] == 'add_axis':
            ig, names, yscale, xlabel, ylabel = command[1:]
            self.data_names[ig] = names
            self.yscales[ig] = yscale
            self.xlabels[ig] = xlabel
            self.ylabels[ig] = ylabel
            self.n_gr = len(self.data_names)
            self.make_axes()

        elif command[0] == 'save':
            self.fig.savefig(command[1])
            self.pipe.send(True)  # Acknowledge save.
Esempio n. 28
0
def plot_sumfile(handle,v,clim=(10,100000)):
    """ Plot UHEL's sum-formatted aerosol number-size distribution """
    
    time = v[1:,0] # This is datenum
    dp = v[0,2:]
    data = v[1:,2:]
    data[data<=0]=1e-30 # No holes in plots
    mesh_dp, mesh_time = np.meshgrid(dp,time)
    pcolorplot = handle.pcolormesh(mesh_time,mesh_dp,data,
                                   norm=colors.LogNorm(),
                                   linewidth=0,rasterized=True,cmap='jet')
    handle.set_yscale('log')
    pcolorplot.set_clim(clim)
    pcolorplot.set_edgecolor('face')
    handle.autoscale(tight='true')
    #handle.set_xlim((np.floor(time[0]),np.floor(time[0])+1)) # makes 24-h axis

    handle.grid('on',which='both',linestyle='--',color='w',lw=0.5)
    handle.xaxis.set_major_locator(dts.HourLocator(interval=1))
    handle.xaxis.set_major_formatter(dts.DateFormatter('%H'))
    #handle.set_xticks(np.floor(time[0])+np.arange(0,25)/24.0)
    #handle.set_xticklabels(["%2.2i" % x for x in np.arange(0,25)])
    plt.setp(handle.get_xticklabels(), rotation=80)
    handle.set_ylabel('Dp, [m]')
    handle.set_xlabel('UTC'+'%+d'%v[0,0]+', [h]')
    cbar = plt.colorbar(pcolorplot, ax=handle, 
                        ticks=LogLocator(subs=range(10)))
    cbar.set_label('dN/dlogDp, [cm-3]')
    return pcolorplot
Esempio n. 29
0
def weight_dist(w_, save_path=None, yscale='log'):
    """
    Plots log distributions of continuous weights in a binary neural network;
    saves output

    Parameters
    ----------
    w_ : list of arrays
            arrays are continous weights
    data_set : str
        data set being used; used for the save file
    """
    x_grid = np.arange(-1, 1, 0.02)
    fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(3, 2),
                             sharex=True, sharey=True)
    for i, w in enumerate(w_):
        pdf = kde_scipy(w.ravel(), x_grid, bandwidth=.1)
        ax = axes
        ax.plot(x_grid, pdf, lw=1, alpha=1.0, label='Layer {}'.format(i+1))
    ax.set_ylim([0.00001, 3])
    ax.xaxis.set_major_locator(MaxNLocator(3))
    if yscale == 'log':
        ax.yaxis.set_major_locator(LogLocator(base=10, numticks=6))
    elif yscale == 'linear':
        ax.yaxis.set_major_locator(MaxNLocator(3))
    else:
        raise ValueError('Invalid yscale')
    ax.set_yscale(yscale)
    plt.legend(loc=8, labelspacing=0.1, prop={'size': 8})
    plt.title('Weight Histogram')
    plt.tight_layout()
    if save_path is not None:
        plt.savefig(save_path)
    return fig, ax
def DrawFigure(x_values, y_values, legend_labels, x_label, y_label, y_min, y_max, filename, allow_legend):
    # you may change the figure size on your own.
    fig = plt.figure(figsize=(10, 3))
    figure = fig.add_subplot(111)

    FIGURE_LABEL = legend_labels

    if not os.path.exists(FIGURE_FOLDER):
        os.makedirs(FIGURE_FOLDER)

    # values in the x_xis
    index = np.arange(len(x_values))
    # the bar width.
    # you may need to tune it to get the best figure.
    width = 0.08
    # draw the bars
    bars = [None] * (len(FIGURE_LABEL))
    for i in range(len(y_values)):
        bars[i] = plt.bar(index + i * width + width / 2,
                          y_values[i], width,
                          hatch=PATTERNS[i],
                          color=LINE_COLORS[i],
                          label=FIGURE_LABEL[i],edgecolor='black', linewidth=3)

    # sometimes you may not want to draw legends.
    if allow_legend == True:
        plt.legend(bars, FIGURE_LABEL,
                   prop=LEGEND_FP,
                   ncol=4,
                   loc='upper center',
                   #                     mode='expand',
                   shadow=False,
                   bbox_to_anchor=(0.45, 1.6),
                   columnspacing=0.1,
                   handletextpad=0.2,
                   #                     bbox_transform=ax.transAxes,
                   #                     frameon=True,
                   #                     columnspacing=5.5,
                   #                     handlelength=2,
                   )

    # you may need to tune the xticks position to get the best figure.
    plt.xticks(index + 5 * width, x_values)
    # plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
    # plt.grid(axis='y', color='gray')
    # figure.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())

    # you may need to tune the xticks position to get the best figure.
    plt.yscale('log')
    #
    # plt.grid(axis='y', color='gray')
    figure.yaxis.set_major_locator(LogLocator(base=10))
    # figure.xaxis.set_major_locator(LinearLocator(5))
    figure.get_xaxis().set_tick_params(direction='in', pad=10)
    figure.get_yaxis().set_tick_params(direction='in', pad=10)

    plt.xlabel(x_label, fontproperties=LABEL_FP)
    plt.ylabel(y_label, fontproperties=LABEL_FP)

    plt.savefig(FIGURE_FOLDER + "/" + filename + ".pdf", bbox_inches='tight')