Esempio n. 1
0
    def get_plot(
        self,
        subplot=False,
        width=None,
        height=None,
        xmin=-6.0,
        xmax=6.0,
        yscale=1,
        colours=None,
        plot_total=True,
        legend_on=True,
        num_columns=2,
        legend_frame_on=False,
        legend_cutoff=3,
        xlabel="Energy (eV)",
        ylabel="DOS",
        zero_to_efermi=True,
        zero_line=False,
        zero_energy=None,
        dpi=400,
        fonts=None,
        plt=None,
        style=None,
        no_base_style=False,
        spin=None,
    ):
        """Get a :obj:`matplotlib.pyplot` object of the density of states.

        Args:
            subplot (:obj:`bool`, optional): Plot the density of states for
                each element on separate subplots. Defaults to ``False``.
            width (:obj:`float`, optional): The width of the plot.
            height (:obj:`float`, optional): The height of the plot.
            xmin (:obj:`float`, optional): The minimum energy on the x-axis.
            xmax (:obj:`float`, optional): The maximum energy on the x-axis.
            yscale (:obj:`float`, optional): Scaling factor for the y-axis.
            colours (:obj:`dict`, optional): Use custom colours for specific
                element and orbital combinations. Specified as a :obj:`dict` of
                :obj:`dict` of the colours. For example::

                    {
                        'Sn': {'s': 'r', 'p': 'b'},
                        'O': {'s': '#000000'}
                    }

                The colour can be a hex code, series of rgb value, or any other
                format supported by matplotlib.
            plot_total (:obj:`bool`, optional): Plot the total density of
                states. Defaults to ``True``.
            legend_on (:obj:`bool`, optional): Plot the graph legend. Defaults
                to ``True``.
            num_columns (:obj:`int`, optional): The number of columns in the
                legend.
            legend_frame_on (:obj:`bool`, optional): Plot a frame around the
                graph legend. Defaults to ``False``.
            legend_cutoff (:obj:`float`, optional): The cut-off (in % of the
                maximum density of states within the plotting range) for an
                elemental orbital to be labelled in the legend. This prevents
                the legend from containing labels for orbitals that have very
                little contribution in the plotting range.
            xlabel (:obj:`str`, optional): Label/units for x-axis (i.e. energy)
            ylabel (:obj:`str`, optional): Label/units for y-axis (i.e. DOS)
            zero_to_efermi (:obj:`bool`, optional): Normalise the plot such
                that the Fermi level is set as 0 eV.
            zero_line (:obj:`bool`, optional): Draw a line at 0 eV.
            zero_energy (:obj:`float`, optional): If provided, this value is
                used as the 0 eV reference. Otherwise, behaviour depends on
                zero_to_efermi.
            dpi (:obj:`int`, optional): The dots-per-inch (pixel density) for
                the image.
            fonts (:obj:`list`, optional): Fonts to use in the plot. Can be a
                a single font, specified as a :obj:`str`, or several fonts,
                specified as a :obj:`list` of :obj:`str`.
            plt (:obj:`matplotlib.pyplot`, optional): A
                :obj:`matplotlib.pyplot` object to use for plotting.
            style (:obj:`list`, :obj:`str`, or :obj:`dict`): Any matplotlib
                style specifications, to be composed on top of Sumo base
                style.
            no_base_style (:obj:`bool`, optional): Prevent use of sumo base
                style. This can make alternative styles behave more
                predictably.
            spin (:obj:`Spin`, optional): Plot a spin-polarised density of
                states, "up" or "1" for spin up only, "down" or "-1" for spin
                down only.  Defaults to ``None``.

        Returns:
            :obj:`matplotlib.pyplot`: The density of states plot.
        """
        plot_data = self.dos_plot_data(
            yscale=yscale,
            xmin=xmin,
            xmax=xmax,
            colours=colours,
            plot_total=plot_total,
            legend_cutoff=legend_cutoff,
            subplot=subplot,
            zero_to_efermi=zero_to_efermi,
            zero_energy=zero_energy,
            spin=spin,
        )

        if subplot:
            nplots = len(plot_data["lines"])
            plt = pretty_subplot(nplots,
                                 1,
                                 width=width,
                                 height=height,
                                 dpi=dpi,
                                 plt=plt)
        else:
            plt = pretty_plot(width=width, height=height, dpi=dpi, plt=plt)

        mask = plot_data["mask"]
        energies = plot_data["energies"][mask]
        fig = plt.gcf()
        lines = plot_data["lines"]
        if len(lines[0][0]["dens"]) == 1:
            spins = [Spin.up]
        elif spin is not None:
            spins = [spin]
        else:
            spins = [Spin.up, Spin.down]

        for i, line_set in enumerate(plot_data["lines"]):
            if subplot:
                ax = fig.axes[i]
            else:
                ax = plt.gca()

            for line, spin in itertools.product(line_set, spins):
                if len(spins) == 1:
                    label = line["label"]
                    densities = line["dens"][spin][mask]
                elif spin is Spin.up:
                    label = line["label"]
                    densities = line["dens"][spin][mask]
                elif spin is Spin.down:
                    label = ""
                    densities = -line["dens"][spin][mask]
                ax.fill_between(
                    energies,
                    densities,
                    lw=0,
                    facecolor=line["colour"],
                    alpha=line["alpha"],
                )
                ax.plot(energies, densities, label=label, color=line["colour"])

            if zero_line:
                draw_themed_line(0, ax, orientation="vertical")

            ax.set_ylim(plot_data["ymin"], plot_data["ymax"])
            ax.set_xlim(xmin, xmax)
            if len(spins) == 1:
                ax.set_ylim(0, plot_data["ymax"])
            else:
                ax.set_ylim(plot_data["ymin"], plot_data["ymax"])

            ax.tick_params(axis="y", labelleft=False)
            ax.yaxis.set_minor_locator(AutoMinorLocator(2))
            ax.xaxis.set_minor_locator(AutoMinorLocator(2))

            loc = "upper right" if subplot else "best"
            ncol = 1 if subplot else num_columns
            if legend_on:
                ax.legend(loc=loc, frameon=legend_frame_on, ncol=ncol)

        # no add axis labels and sort out ticks
        if subplot:
            ax.set_xlabel(xlabel)
            fig.subplots_adjust(hspace=0)
            plt.setp([a.get_xticklabels() for a in fig.axes[:-1]],
                     visible=False)
            if "axes.labelcolor" in matplotlib.rcParams:
                ylabelcolor = matplotlib.rcParams["axes.labelcolor"]
            else:
                ylabelcolor = None

            fig.text(
                0.08,
                0.5,
                ylabel,
                ha="left",
                color=ylabelcolor,
                va="center",
                rotation="vertical",
                transform=ax.transAxes,
            )
        else:
            ax.set_xlabel(xlabel)
            ax.set_ylabel(ylabel)

        return plt
Esempio n. 2
0
    def plot_DLA(self, z, logN=None, v_corr=0, v_space=500, normalized=False, 
                 save=False, debug=False, verbose=False):
        """
        parameters:
            - z           : redshift of the DLA
            - logN        : column density of HI absorber
            - v_corr      : velocity offset for correction of the z_DLA, in km/s
            - v_space     : x_axis range
            - normalized  : plot normalized specrtum
            - save        : save figure
        """
        c = const.c.cgs.value
        z_DLA = (1 + z) * (1 + v_corr * 1e5/ c) - 1

        n_rows, n_cols = 15, 2 #int(len(lines) / 2) + 1

        # set x and y axis scale
        x_minorLocator = AutoMinorLocator(9)
        x_locator = MultipleLocator(100)
        # y_minorLocator = AutoMinorLocator(9)
        # y_locator = MultipleLocator(1.0)
        y_min = -0.1
        y_max = 1.4

        width = 35
        h_size = width * n_cols + 1
        height = 20
        v_size = height * n_rows + 1
        
        lines = atomicData.DLA_minor()
        num = len(lines)
        
        if n_cols > 1 and n_rows > 1:
            fig, ax = plt.subplots(n_rows, n_cols, figsize=(20, 40))

            l = -1
            col = 0
            for line in lines:
                lambda_0 = line.l * (1 + z_DLA)
                if verbose:
                    print(line, lambda_0)
                
                if str(line) == 'HI 1215':
                    vel_space = max(v_space, lorenz_range(0.05, logN=logN, line=line) + 100)
                    x_minorLocator = AutoMinorLocator(4)
                    x_locator = MultipleLocator(500)
                elif str(line) == 'HI 1025':
                    vel_space = max(v_space, lorenz_range(0.05, logN=logN, line=line) + 100)
                    x_minorLocator = AutoMinorLocator(3)
                    x_locator = MultipleLocator(400)
                else:
                    vel_space = v_space
                    x_minorLocator = AutoMinorLocator(9)
                    x_locator = MultipleLocator(100)

                # find y_min, y_max:
                if verbose:
                    print('range: ', lambda_0 * (1 - vel_space * 1e5 / c), lambda_0 * (1 + vel_space * 1e5 / c))
                    
                i_min, i_max = np.searchsorted(self.norm[0], lambda_0 * (1 - vel_space * 1e5 / c)), np.searchsorted(
                    self.norm[0], lambda_0 * (1 + vel_space * 1e5 / c))
                # print(i_min, i_max)
                if i_min < i_max:
                    if line.name == 'HI' and col == 0:
                        col = 1
                        l = -1
                    
                    l = l + 1
                    row = l

                    if line.name == 'HI':
                        y_min, y_max = -0.1, 1.3
                    else:
                        y_min, y_max = minmax(self.norm[1][i_min:i_max])
                    # y_min, y_max = np.amin(qso[1][i_min:i_max]), np.amax(qso[1][i_min:i_max])

                    axs = ax[row, col]
                    # >>> plot spectrum
                    axs.errorbar((self.norm[0][i_min:i_max] / lambda_0 - 1) * c / 1e5,
                                 self.norm[1][i_min:i_max],self.norm[2][i_min:i_max],
                                 lw=0.75, elinewidth=0.5, drawstyle='steps-mid',
                                 color='k', ecolor='0.3', capsize=3)

                    # >>> set axis
                    axs.axis([-vel_space, vel_space, y_min, y_max])

                    # >>> set labels
                    if col == 0 and col == n_cols / 2:
                        axs.set_ylabel('Normalized flux', fontsize=font)
                    if row == n_rows - 1:
                        axs.set_xlabel('v [km/s]', fontsize=font)

                    # >>> set text
                    axs.text(-vel_space * 0.9, y_min, line, color='red', fontsize=font, 
                             ha='left', va='bottom')

                    # >>> set ticks
                    axs.xaxis.set_minor_locator(x_minorLocator)
                    axs.xaxis.set_major_locator(x_locator)
                    axs.yaxis.set_major_locator(MaxNLocator(nbins=4))
                    axs.tick_params(which='major', length=5, width=1, labelsize=font - 2)
                    axs.tick_params(which='minor', length=3, width=1)
                    
                    # >>> set lines
                    axs.plot([-vel_space, vel_space], [0.0, 0.0], 'k--', lw=0.5)
                    axs.plot([0, 0], [y_min, y_max], color='#aa0000', linestyle='--', lw=1.5)
                    if line.name == 'HI':
                        axs.plot([-81.6, -81.6], [y_min, y_max], color='#0000aa', linestyle='--', lw=1.5)

                    # >>> plot absorption lines
                    if logN is not None:
                        wscale = np.linspace(self.norm[0][i_min], self.norm[0][i_max], (i_max-i_min)*3)
                        if line.name == 'HI':
                            # add HI lines
                            v_0 = (wscale / lambda_0 - 1) * c / 1e5
                            tau = calctau(v_0, line.l, line.f, line.g, logN, 20.0, vel=True)
                            axs.plot(v_0, convolveflux(v_0, np.exp(-tau), res=20000, vel=True), '-r', lw=1.5)
                            # add DI lines
                            v = (wscale / lambda_0 / (1 - 81.6e5 / c) - 1) * c / 1e5
                            tau = calctau(v, line.l, line.f, line.g, logN - 4.55, 19.0, vel=True)
                            
                            axs.plot(v_0, convolveflux(v_0, np.exp(-tau), res=20000, vel=True), '-b', lw=1.5)

            fig.suptitle(q.id + ', z=' + str(z), fontsize=14)
        print(q.id + '.pdf')
        plt.savefig(q.id + '.pdf', bbox_inches='tight', pad_inches=0.1)
        plt.show()
Esempio n. 3
0
    def plot(self, run_configurations, axes):
        num_argument_sets = len(self.argument_sets)
        if num_argument_sets == 0:
            return

        sorted_argument_sets = self.sort_argument_sets(
            isolate_keys=[])  # No sort applied, but labels provided
        argument_diff = cr.ArgumentSetDifference(
            self.argument_sets, ignore_keys=self._get_sweep_keys())
        differences = argument_diff.get_differences()
        test = []
        xLabel = []
        for key in differences:
            xLabel.append(key)
        for argument_set_hash, argument_sets in sorted_argument_sets.items():
            argument_set = argument_sets[0]
            precision = argument_set.get("compute_type").get_value()
            function = argument_set.get("function").get_value()
            for key in differences:
                argument = argument_set.get(key)
                test.append(
                    argument.get_value() if argument.is_set() else 'DEFAULT')
                break

        grouped_run_configurations = run_configurations.group_by_label()

        num_groups = len(grouped_run_configurations)
        metric_labels = [
            key for key in self.argument_sets[0].collect_timing(
                run_configurations[0])
        ]
        num_metrics = len(metric_labels)
        if num_metrics == 0:
            return

        # loop over independent outputs
        y_scatter_by_group = OrderedDict()
        for group_label, run_configuration_group in grouped_run_configurations.items(
        ):
            # x_scatter_by_group[group_label] = []
            y_scatter_by_group[group_label] = []
            # loop over argument sets that differ other than the swept variable(s)
            for subset_label, partial_argument_sets in sorted_argument_sets.items(
            ):
                if len(partial_argument_sets) != 1:
                    raise ValueError(
                        'Assumed that sorting argument sets with no keys has a single element per sort.'
                    )
                argument_set = partial_argument_sets[0]
                y_list_by_metric = OrderedDict(
                )  # One array of y values for each metric
                # loop over number of coarse grain runs and concatenate results
                for run_configuration in run_configuration_group:
                    results = argument_set.collect_timing(run_configuration)
                    for metric_label in results:
                        if not metric_label in y_list_by_metric:
                            y_list_by_metric[metric_label] = []
                        y_list_by_metric[metric_label].extend(
                            results[metric_label])
                # For each metric, add a set of bars in the bar chart.
                for metric_label, y_list in y_list_by_metric.items():
                    y_scatter_by_group[group_label].extend(sorted(y_list))

        for group_label, run_configuration_group in grouped_run_configurations.items(
        ):
            for run_configuration in run_configuration_group:
                mclk = run_configuration.load_specifications(
                )['ROCm Card0']["Start mclk"].split("Mhz")[0]
                sclk = run_configuration.load_specifications(
                )['ROCm Card0']["Start sclk"].split("Mhz")[0]
                theoMax = 0
                precisionBits = int(re.search(r'\d+', precision).group())
                if (function == 'gemm' and precisionBits == 32):  #xdlops
                    theoMax = float(
                        sclk
                    ) / 1000.00 * 256 * 120  #scaling to appropriate precision
                elif (
                        function == 'trsm' or function == 'gemm'
                ):  #TODO better logic to decide memory bound vs compute bound
                    theoMax = float(
                        sclk
                    ) / 1000.00 * 128 * 120 * 32.00 / precisionBits  #scaling to appropriate precision
                elif self.flops and self.mem:
                    try:
                        n = 100000
                        flops = eval(self.flops)
                        mem = eval(self.mem)
                        theoMax = float(mclk) / float(eval(self.mem)) * eval(
                            self.flops) * 32 / precisionBits / 4
                    except:
                        print("flops and mem equations produce errors")
                if theoMax:
                    theoMax = round(theoMax)
                    x_co = (test[0], test[len(test) - 1])
                    y_co = (theoMax, theoMax)
                    axes.plot(x_co,
                              y_co,
                              label="Theoretical Peak Performance: " +
                              str(theoMax) + " GFLOP/s")

        for group_label in y_scatter_by_group:
            axes.scatter(
                # x_bar_by_group[group_label],
                test,
                y_scatter_by_group[group_label],
                # gap_scalar * width,
                color='black',
                # label = group_label,
            )
            axes.plot(
                # x_scatter_by_group[group_label],
                test,
                y_scatter_by_group[group_label],
                # 'k*',
                '-ok',
            )

        axes.xaxis.set_minor_locator(AutoMinorLocator())
        axes.yaxis.set_minor_locator(AutoMinorLocator())

        axes.set_ylabel(metric_labels[0] if len(metric_labels) ==
                        1 else 'Time (s)')
        axes.set_xlabel('='.join(xLabel))
        return True
Esempio n. 4
0
                #ax1.minorticks_on()
                ax1.grid(which='major',
                         axis='both',
                         color='black',
                         linestyle='-',
                         zorder=3)
                ax1.grid(which='minor',
                         axis='both',
                         color='grey',
                         linestyle='-',
                         zorder=3)

                majorLocator = MultipleLocator(.10)
                ax1.yaxis.set_major_locator(majorLocator)
                ax1.xaxis.set_minor_locator(AutoMinorLocator(2))
                ax1.set_xlabel('Elevation')
                ax1.set_ylabel('Area (% Below)')
                ax1.set_ylim([-0.05, 1.05])

                #add plot legend with location and size
                ax1.legend(loc='upper left', prop={'size': 10})

                plt.title(name + ' Area Elevation Curve')

                output_folder = csv_file_out + '\\AEC_plots\\'
                if os.path.exists(output_folder) == False:
                    os.makedirs(output_folder)
                figname = output_folder + name + '_AEC_slim.png'

                plt.savefig(figname, dpi=100)
Esempio n. 5
0
                                file_labels=file_labels,
                                linewidth=1.5)
#    plot_iter = plot_profiles(profs, plot_iter, nplotx, nploty, axarr, xscaledict, yscaledict, xlimdict_profs, ylimdict_profs, ylabel='', file_names=file_names, file_labels=file_labels)

# legend font size
plt.rcParams.update({'font.size': 10})

#axes = plt.gca()
#axes.tick_params(direction='in')
labeldict = ["{\it ScNc30}", "{\it ScNc45}", "{\it ScNc105}"]
y_arr = np.arange(nploty)
for y in y_arr:
    #tics inside
    axarr[y].tick_params(direction='in', which='both', top=1, right=1)
    #minor tics
    axarr[y].xaxis.set_minor_locator(AutoMinorLocator())
    axarr[y].yaxis.set_minor_locator(AutoMinorLocator())
    #labels and tics font size
    for item in (axarr[y].get_xticklabels() + axarr[y].get_yticklabels()):
        item.set_fontsize(8)
    for item in ([axarr[y].xaxis.label, axarr[y].yaxis.label]):
        item.set_fontsize(10)
    # subplot numbering
#    if y < nploty - nemptyplots or x < (nplotx - 1):
#     axarr[y].text(0.8, 0.9, labeldict[y + x*nploty], fontsize=8, transform=axarr[y].transAxes)
    axarr[y].text(0.05,
                  0.92,
                  labeldict[y],
                  fontsize=10,
                  transform=axarr[y].transAxes)
Esempio n. 6
0
sigma_ns = np.asarray(
    map(lambda v: (v[1] - v[0]),
        zip(*np.percentile(NStrackarray, [50, 68], axis=0))))

print(np.shape(EWtrackarray))
'''
Plotting
'''
csfont = {'fontname': 'Gill Sans MT'}

# set
majorLocator = MultipleLocator(1)
majorFormatter = FormatStrFormatter('%d')
minorLocatorx = MultipleLocator(0.1)
# minorLocatory  =  MultipleLocator(1)
minorLocator1 = AutoMinorLocator(n=2)

fig, axarr = pl.subplots(2, sharex=True)
# fig.suptitle(target, fontweight='normal', fontsize = 16,**csfont )
axarr[1].xaxis.set_major_locator(majorLocator)
axarr[1].xaxis.set_major_formatter(majorFormatter)
axarr[1].xaxis.set_minor_locator(minorLocatorx)
# axarr[1].yaxis.set_minor_locator(minorLocatory)

# Plot North offset with 1 and 2 sigma errors
axarr[0].plot(tl, NS_vector, color="black", lw=1.5, alpha=1)
axarr[0].fill_between(tl,
                      NS_vector - sigma_ns,
                      NS_vector + sigma_ns,
                      alpha=0.25,
                      color='black',
Esempio n. 7
0
T=HourBefore
for a in range(0,7):
    TS=gmtime(T)
    TS=list(TS)
    if TS[4] < 10:
        TS[4]="0"+str(TS[4])
        
        
    Tick=str(TS[3])+":"+str(TS[4])
    Ticks.append(Tick)
    Locs.append(T)
    T+=600


# Now Generate plots
L=AutoMinorLocator(4)
for i in range(0,10):

    plt.figure(figsize=(8,6))
    a=plt.plot(Time,Data[i],'ro',markersize=.25)
    plt.axes().yaxis.set_minor_locator(L)
    plt.grid(1)
    plt.xlabel('Time')
    plt.ylabel("Current (A)")
    plt.xticks(Locs,Ticks)
    plt.ylim([9,18])
    plt.xlim([HourBefore,(T-600)])
    string="Graph of Current vs Time for CH "+str(i+1)
    plt.title(string)
    name="WebServer/RPI1/HourLongPlots/CH"+str(i+1)+".png"
    plt.savefig(name)
Esempio n. 8
0
    def fill_axis(self, ax, text):
        # Plot image as a colour map
        cmap = ax.imshow(self.im,
                         extent=self.extent,
                         vmin=np.min(self.im),
                         vmax=np.max(self.im),
                         cmap=colormaps.jesse_reds)

        if self.rms:
            # Set contour levels
            cont_levs = np.arange(3, 100, 3) * self.rms
            # add residual contours if resdiual exists; otherwise, add image contours
            try:
                ax.contour(self.resid,
                           levels=cont_levs,
                           colors='k',
                           linewidths=0.75,
                           linestyles='solid')
                ax.contour(self.resid,
                           levels=-1 * np.flip(cont_levs, axis=0),
                           colors='k',
                           linewidths=0.75,
                           linestyles='dashed')
            except AttributeError:
                ax.contour(self.ra_offset,
                           self.dec_offset,
                           self.im,
                           colors='k',
                           levels=cont_levs,
                           linewidths=0.75,
                           linestyles='solid')
                ax.contour(self.ra_offset,
                           self.dec_offset,
                           self.im,
                           levels=-1 * np.flip(cont_levs, axis=0),
                           colors='k',
                           linewidths=0.75,
                           linestyles='dashed')

        # Create the colorbar
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("top", size="8%", pad=0.0)
        cbar = self.fig.colorbar(cmap,
                                 ax=ax,
                                 cax=cax,
                                 orientation='horizontal')
        cbar.ax.xaxis.set_tick_params(direction='out',
                                      length=3,
                                      which='major',
                                      bottom='off',
                                      top='on',
                                      labelsize=8,
                                      pad=-2,
                                      labeltop='on',
                                      labelbottom='off')

        cbar.ax.xaxis.set_tick_params(direction='out',
                                      length=2,
                                      which='minor',
                                      bottom='off',
                                      top='on')

        if np.max(self.im) > 500:
            tickmaj = 200
            tickmin = 50
        elif np.max(self.im) > 200:
            tickmaj = 100
            tickmin = 25
        elif np.max(self.im) > 100:
            tickmaj = 50
            tickmin = 10
        elif np.max(self.im) <= 100:
            tickmaj = 20
            tickmin = 5

        minorLocator = AutoMinorLocator(tickmaj / tickmin)
        cbar.ax.xaxis.set_minor_locator(minorLocator)
        cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(),
                                rotation=45,
                                fontsize=18)
        cbar.set_ticks(np.arange(-10 * tickmaj, 10 * tickmaj, tickmaj))

        # Colorbar label
        cbar.ax.text(
            0.425,
            0.320,
            r'$\mu Jy / beam$',
            fontsize=12,
            path_effects=[PathEffects.withStroke(linewidth=2, foreground="w")])

        # Overplot the beam ellipse
        try:
            beam_ellipse_color = 'k'
            bmin = self.head['bmin'] * 3600.
            bmaj = self.head['bmaj'] * 3600.
            bpa = self.head['bpa']

            el = Ellipse(xy=[4.2, -4.2],
                         width=bmin,
                         height=bmaj,
                         angle=-bpa,
                         edgecolor='k',
                         hatch='///',
                         facecolor='none',
                         zorder=10)
            ax.add_artist(el)
        except KeyError:
            pass

        # Plot the scale bar
        if np.where(self.axes == ax)[1][0] == 0:  #if first plot
            x = -3.015
            y = -4.7
            ax.plot([x, x - 10 / 9.725], [y, y], '-', linewidth=2, color='k')
            ax.text(x + 0.32,
                    y + 0.15,
                    "10 au",
                    fontsize=18,
                    path_effects=[
                        PathEffects.withStroke(linewidth=2, foreground="w")
                    ])

        # Plot a cross at the source position
        # ax.plot([0.0], [0.0], '+', markersize=6, markeredgewidth=1, color='w')

        # Add figure text
        if text is not None:
            for t in text:
                ax.text(*t,
                        fontsize=18,
                        path_effects=[
                            PathEffects.withStroke(linewidth=3, foreground="w")
                        ])

        if self.title:
            plt.suptitle(self.title)
def getYCoordinateForConfigName(top_y):
    return int(0.5 * top_y)


#############################################################
############# MEDIAN LATENCY OVER 1 MINUTE ##################
#############################################################
fig, ax = plt.subplots()

ax.set_yscale('log')
#print list_median_latency
ax.plot(list_median_start_time_min, list_median_latency, color='b')

ax.set_xlim(xmin=0)
ax.xaxis.set_ticks(np.arange(0, max(list_ts_min) + 11, 10))
x_minorLocator = AutoMinorLocator(5)
ax.xaxis.set_minor_locator(x_minorLocator)
ax.grid(color='dimgrey', which='major', axis='x')
ax.grid(color='gainsboro', which='minor', axis='x')

ax.grid(color='black', which='major', axis='y')
ax.grid(color='gainsboro', which='minor', axis='y')

i = 0
for i in range(len(list_rebalance_times_min)):
    r_time = list_rebalance_times_min[i]
    if i != 0:
        plt.axvline(x=r_time,
                    color='darkorange',
                    linestyle='dashed',
                    linewidth=2.5)
Esempio n. 10
0
# plot
ax1.plot(df['vrot_rpm'], df['maxT_degC'], 's-', color="darkblue", linewidth=1)
# axes label
ax1.set_ylabel(r'\textbf{Maximum target temperature [$^{\circ}$C]}',
               fontsize=12,
               labelpad=10)
ax1.set_xlabel(r'\textbf{Target rotational speed [rpm]}',
               fontsize=12,
               labelpad=10)

# ticks
ax1.xaxis.set_ticks([25, 200, 300, 500, 750, 1000])
ax1.xaxis.set_ticks(np.arange(0, 1250, 250))
ax1.yaxis.set_ticks(np.arange(100, 260 + 40, 40))
# minor ticks x
minor_locator = AutoMinorLocator(2)
ax1.xaxis.set_minor_locator(minor_locator)
# minor ticks y
minor_locator = AutoMinorLocator(2)
ax1.yaxis.set_minor_locator(minor_locator)
# tick font size
ax1.tick_params('x', colors='black', labelsize=12)
ax1.tick_params('y', colors='black', labelsize=12)
# grid
ax1.grid(b=True, which='major', linestyle='-')  #, color='gray')
ax1.grid(b=True, which='minor', linestyle='--')  #, color='gray')

# ####################
# # other axis
# ####################
# ax2 = ax1.twinx()
Esempio n. 11
0
    def create_colour_chart(self, kmax):
        """
        Creates a 2D colour chart of integer solutions vs board dimensions.
        Ref: https://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/
        interpolate.html#two-dimensional-spline-representation-procedural-bisplrep
        self.solutions: (dict)solutions for algorithm 'name'.
        self.algorithm: (string)algorithm name.
        :param kmax: (int)maximum m or n dimension: m = n = (kmax - 1).
        :return: n/a
        """
        print("Results Graph: processing results for the {} algorithm."
              .format(self.algorithm))
        # Extract all the keys, these represent the mxn board dimensions and
        # indicate what has been tested.
        keys = self.solutions.keys()
        # Extract the dimensions; use a regex
        # We need these values to size the graph correctly
        regex_mxn = re.compile(r"(\d+)x(\d+)", re.IGNORECASE)
        # Now create a colour chart with the data
        fig, ax = plt.subplots(2, 2, figsize=(13, 9))
        # Process each figure plot in turn: column by column and row by row
        for row in range(2):
            # Set the solution index to either all or fundamental solutions
            if row:
                idx = I_FUNSOLNS
            else:
                idx = I_ALLSOLNS
            for col in range(2):
                z_all = np.array([], np.uint32)
                points = np.array([], np.uint32)
                for keystr in keys:
                    mxn_tuple = re.findall(regex_mxn, keystr)
                    # Record all the points in arrays
                    # Populate the z_all array
                    m_current = int(mxn_tuple[0][0])
                    n_current = int(mxn_tuple[0][1])
                    z_all = np.append(z_all, self.solutions[keystr][idx])
                    points = np.append(points, [m_current, n_current])
                # Reshape the array into coordinates (m, n)
                points = np.reshape(points, (int(len(points) / 2), 2))
                # Reshape the results array z_all
                z_all = np.reshape(z_all, (int(len(z_all)), ))
                # np.linspace(start, stop, number of points)
                # eg. np.linspace(0, 100, 5) => 0, 25, 50, 75, 100
                if col == 1:
                    # High resolution grid - fascinating alternate view for colour map
                    grid_x, grid_y = np.meshgrid(np.linspace(1, kmax, kmax * 10),
                                                 np.linspace(1, kmax, kmax * 10))
                else:
                    # Low resolution grid
                    grid_x, grid_y = np.meshgrid(np.linspace(1, kmax, kmax),
                                                 np.linspace(1, kmax, kmax))
                grid_z = griddata(points, z_all, (grid_x, grid_y), method='cubic')

                # Add a single chart to the 2 x 2 figure
                ax[row, col].imshow(grid_z.T, extent=(0, kmax, 0, kmax), origin='lower')
                # Configure the major ticks; starting at -0.5 to ensure the
                # grid/board is drawn completely
                ax[row, col].set_xticks(list(range(kmax)), minor=False)
                ax[row, col].set_yticks(list(range(kmax)), minor=False)
                # Hide the labels for the major ticks on both axis.
                ax[row, col].tick_params(axis='both', which='major', labelcolor='white')
                # Configure the minor ticks; we want to use these to number the
                # rows and columns and centre them at the edge of each square.
                # Remember the rows and columns start at the bottom left corner
                # with at (0, 0).
                ax[row, col].xaxis.set_minor_locator(AutoMinorLocator(2))
                ax[row, col].yaxis.set_minor_locator(AutoMinorLocator(2))
                # Add the text labels to the minor ticks for both rows and columns.
                col_labels = [str(x + 1) for x in range(kmax)]
                ax[row, col].set_xticklabels(col_labels, minor=True)
                row_labels = [str(y + 1) for y in range(kmax)]
                ax[row, col].set_yticklabels(row_labels, minor=True)
                # Hide the ticks on both axis; looks better.
                ax[row, col].tick_params(axis='both', which='both', length=0.0)
                if idx == I_ALLSOLNS:
                    ax[row, col].set_title('All', fontsize=16)
                else:
                    ax[row, col].set_title('Fundamental', fontsize=16)
                ax[row, col].set_xlabel('m', fontsize=16)
                ax[row, col].set_ylabel('n', fontsize=16)
        # Set the graph size
        fig.suptitle("{} Solutions".format(self.algorithm),
                     fontsize=18, weight='bold')
        plt.subplots_adjust(hspace=0.3)
        # Have all the data to write out to a results file.
        fname = os.path.join(cmn.RESULTS_FOLDER,
                             "{}_solutions.png".format(self.algorithm))
        plt.savefig(fname)
#        plt.show() # debug
        print("Created {}".format(fname))
Esempio n. 12
0
def main():
    # -------------------------------------------------------------------------
    # Simulation parameters
    # -------------------------------------------------------------------------

    # Borehole dimensions
    D = 4.0  # Borehole buried depth (m)
    H = 150.0  # Borehole length (m)
    r_b = 0.075  # Borehole radius (m)
    B = 7.5  # Borehole spacing (m)

    # Pipe dimensions
    rp_out = 0.0211  # Pipe outer radius (m)
    rp_in = 0.0147  # Pipe inner radius (m)
    D_s = 0.052  # Shank spacing (m)
    epsilon = 1.0e-6  # Pipe roughness (m)

    # Pipe positions
    # Single U-tube [(x_in, y_in), (x_out, y_out)]
    pos_pipes = [(-D_s, 0.), (D_s, 0.)]

    # Ground properties
    alpha = 1.0e-6  # Ground thermal diffusivity (m2/s)
    k_s = 2.0  # Ground thermal conductivity (W/m.K)

    # Grout properties
    k_g = 1.0  # Grout thermal conductivity (W/m.K)

    # Pipe properties
    k_p = 0.4  # Pipe thermal conductivity (W/m.K)

    # Fluid properties
    m_flow = 0.25  # Total fluid mass flow rate per borehole (kg/s)
    cp_f = 3977.  # Fluid specific isobaric heat capacity (J/kg.K)
    den_f = 1015.  # Fluid density (kg/m3)
    visc_f = 0.00203  # Fluid dynamic viscosity (kg/m.s)
    k_f = 0.492  # Fluid thermal conductivity (W/m.K)

    # Number of segments per borehole
    nSegments = 12

    # Geometrically expanding time vector.
    dt = 100 * 3600.  # Time step
    tmax = 3000. * 8760. * 3600.  # Maximum time
    Nt = 50  # Number of time steps
    ts = H**2 / (9. * alpha)  # Bore field characteristic time
    time = gt.utilities.time_geometric(dt, tmax, Nt)

    # -------------------------------------------------------------------------
    # Borehole field
    # -------------------------------------------------------------------------

    # Field of 6x4 (n=24) boreholes
    N_1 = 6
    N_2 = 4
    boreField = gt.boreholes.rectangle_field(N_1, N_2, B, B, H, D, r_b)

    # -------------------------------------------------------------------------
    # Initialize pipe model
    # -------------------------------------------------------------------------

    # Pipe thermal resistance
    R_p = gt.pipes.conduction_thermal_resistance_circular_pipe(
        rp_in, rp_out, k_p)
    # Fluid to inner pipe wall thermal resistance (Single U-tube)
    h_f = gt.pipes.convective_heat_transfer_coefficient_circular_pipe(
        m_flow, rp_in, visc_f, den_f, k_f, cp_f, epsilon)
    R_f = 1.0 / (h_f * 2 * pi * rp_in)

    # Single U-tube, same for all boreholes in the bore field
    UTubes = []
    for borehole in boreField:
        SingleUTube = gt.pipes.SingleUTube(pos_pipes, rp_in, rp_out, borehole,
                                           k_s, k_g, R_f + R_p)
        UTubes.append(SingleUTube)

    # -------------------------------------------------------------------------
    # Evaluate the g-functions for the borefield
    # -------------------------------------------------------------------------

    # Calculate the g-function for uniform heat extraction rate
    gfunc_uniform_Q = gt.gfunction.uniform_heat_extraction(boreField,
                                                           time,
                                                           alpha,
                                                           disp=True)

    # Calculate the g-function for uniform borehole wall temperature
    gfunc_uniform_T = gt.gfunction.uniform_temperature(boreField,
                                                       time,
                                                       alpha,
                                                       nSegments=nSegments,
                                                       disp=True)

    # Calculate the g-function for equal inlet fluid temperature
    gfunc_equal_Tf_in = gt.gfunction.equal_inlet_temperature(
        boreField,
        UTubes,
        m_flow,
        cp_f,
        time,
        alpha,
        nSegments=nSegments,
        disp=True)

    # -------------------------------------------------------------------------
    # Plot g-functions
    # -------------------------------------------------------------------------

    plt.rc('figure')
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    # g-functions
    ax1.plot(np.log(time / ts),
             gfunc_uniform_Q,
             'k-',
             lw=1.5,
             label='Uniform heat extraction rate')
    ax1.plot(np.log(time / ts),
             gfunc_uniform_T,
             'b--',
             lw=1.5,
             label='Uniform borehole wall temperature')
    ax1.plot(np.log(time / ts),
             gfunc_equal_Tf_in,
             'r-.',
             lw=1.5,
             label='Equal inlet temperature')
    ax1.legend()
    # Axis labels
    ax1.set_xlabel(r'$ln(t/t_s)$')
    ax1.set_ylabel(r'$g(t/t_s)$')
    # Axis limits
    ax1.set_xlim([-10.0, 5.0])
    ax1.set_ylim([0., 50.])
    # Show minor ticks
    ax1.xaxis.set_minor_locator(AutoMinorLocator())
    ax1.yaxis.set_minor_locator(AutoMinorLocator())
    # Adjust to plot window
    plt.tight_layout()

    return
Esempio n. 13
0
def plot(
        ecg, 
        sample_rate    = 500, 
        title          = 'ECG 12', 
        lead_index     = lead_index, 
        lead_order     = None,
        style          = None,
        columns        = 2,
        row_height     = 6,
        show_lead_name = True,
        show_grid      = True,
        show_separate_line  = True,
        ):
    """Plot multi lead ECG chart.
    # Arguments
        ecg        : m x n ECG signal data, which m is number of leads and n is length of signal.
        sample_rate: Sample rate of the signal.
        title      : Title which will be shown on top off chart
        lead_index : Lead name array in the same order of ecg, will be shown on 
            left of signal plot, defaults to ['I', 'II', 'III', 'aVR', 'aVL', 'aVF', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6']
        lead_order : Lead display order 
        columns    : display columns, defaults to 2
        style      : display style, defaults to None, can be 'bw' which means black white
        row_height :   how many grid should a lead signal have,
        show_lead_name : show lead name
        show_grid      : show grid
        show_separate_line  : show separate line
    """

    if not lead_order:
        lead_order = list(range(0,len(ecg)))
    secs  = len(ecg[0])/sample_rate
    leads = len(lead_order)
    rows  = int(ceil(leads/columns))
    # display_factor = 2.5
    display_factor = 1
    line_width = 0.5
    fig, ax = plt.subplots(figsize=(secs*columns * display_factor, rows * row_height / 5 * display_factor))
    display_factor = display_factor ** 0.5
    fig.subplots_adjust(
        hspace = 0, 
        wspace = 0,
        left   = 0,  # the left side of the subplots of the figure
        right  = 1,  # the right side of the subplots of the figure
        bottom = 0,  # the bottom of the subplots of the figure
        top    = 1
        )

    fig.suptitle(title)

    x_min = 0
    x_max = columns*secs
    y_min = row_height/4 - (rows/2)*row_height
    y_max = row_height/4

    if (style == 'bw'):
        color_major = (0.4,0.4,0.4)
        color_minor = (0.75, 0.75, 0.75)
        color_line  = (0,0,0)
    else:
        color_major = (1,0,0)
        color_minor = (1, 0.7, 0.7)
        color_line  = (0,0,0.7)

    if(show_grid):
        ax.set_xticks(np.arange(x_min,x_max,0.2))    
        ax.set_yticks(np.arange(y_min,y_max,0.5))

        ax.minorticks_on()
        
        ax.xaxis.set_minor_locator(AutoMinorLocator(5))

        ax.grid(which='major', linestyle='-', linewidth=0.5 * display_factor, color=color_major)
        ax.grid(which='minor', linestyle='-', linewidth=0.5 * display_factor, color=color_minor)

    ax.set_ylim(y_min,y_max)
    ax.set_xlim(x_min,x_max)


    for c in range(0, columns):
        for i in range(0, rows):
            if (c * rows + i < leads):
                y_offset = -(row_height/2) * ceil(i%rows)
                # if (y_offset < -5):
                #     y_offset = y_offset + 0.25

                x_offset = 0
                if(c > 0):
                    x_offset = secs * c
                    if(show_separate_line):
                        ax.plot([x_offset, x_offset], [ecg[t_lead][0] + y_offset - 0.3, ecg[t_lead][0] + y_offset + 0.3], linewidth=line_width * display_factor, color=color_line)

         
                t_lead = lead_order[c * rows + i]
         
                step = 1.0/sample_rate
                if(show_lead_name):
                    ax.text(x_offset + 0.07, y_offset - 0.5, lead_index[t_lead], fontsize=9 * display_factor)
                ax.plot(
                    np.arange(0, len(ecg[t_lead])*step, step) + x_offset, 
                    ecg[t_lead] + y_offset,
                    linewidth=line_width * display_factor, 
                    color=color_line
                    )
Esempio n. 14
0
#make the plot
fig, ax = plt.subplots()

ax.scatter(x, y, color='#005bd3', marker='.', edgecolor='k', linewidth=0.7)
#ax.scatter(x_psi, y_psi, color='C1', marker='^', edgecolor='k', linewidth=0.7, label='psiblast hits')

# axis labels
plt.xlabel('hit length/ query length ratio')
plt.ylabel('bitscore')

#add xticks, label every second xtick
#plt.xticks(np.arange(0.5, 1.1, 0.1))
#for label in ax.xaxis.get_ticklabels()[-1:]:
#	label.set_visible(False)
#plt.yticks(range(50, 110, 10))
ax.xaxis.set_minor_locator(AutoMinorLocator(n=2))
ax.yaxis.set_minor_locator(
    AutoMinorLocator(n=2))  # turn on minor ticks to be for every 1 bin

#turn on y-axis gridlines
ax.yaxis.grid(b=True, which='major', linestyle='--', color='0.9')
ax.yaxis.grid(b=True, which='minor', linestyle='--', color='0.9')
plt.tick_params(axis='y', which='minor', length=0)
ax.set_axisbelow(True)

#figure size
fig.set_size_inches(6, 4)

#position legend, show plot
plt.legend()
plt.tight_layout()
Esempio n. 15
0
Y1 = 3 + np.cos(X)
Y2 = 1 + np.cos(1 + X / 0.75) / 2
Y3 = np.random.uniform(Y1, Y2, len(X))

fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(1, 1, 1, aspect=1)


def minor_tick(x, pos):
    if not x % 1.0:
        return ""
    return "%.2f" % x


ax.xaxis.set_major_locator(MultipleLocator(1.000))
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_major_locator(MultipleLocator(1.000))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick))

ax.set_xlim(0, 4)
ax.set_ylim(0, 4)

ax.tick_params(which='major', width=1.0)
ax.tick_params(which='major', length=10)
ax.tick_params(which='minor', width=1.0, labelsize=10)
ax.tick_params(which='minor', length=5, labelsize=10, labelcolor='0.25')

ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)

ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10)
Esempio n. 16
0
def main():

    # Plot VLE envelopes
    clrs = seaborn.color_palette('bright', n_colors=len(df_r32))
    np.random.seed(11)
    np.random.shuffle(clrs)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))
    temps_r32 = R32.expt_liq_density.keys()
    temps_r125 = R125.expt_liq_density.keys()
    for temp in temps_r32:
        ax1.scatter(
            df_r32.filter(regex=(f"liq_density_{float(temp):.0f}K")),
            np.tile(temp, len(df_r32)),
            c=clrs,
            s=160,
            alpha=0.2,
        )
        ax1.scatter(
            df_r32.filter(regex=(f"vap_density_{float(temp):.0f}K")),
            np.tile(temp, len(df_r32)),
            c=clrs,
            s=160,
            alpha=0.2,
        )
    ax1.scatter(
        df_r32.filter(regex=("sim_rhoc")),
        df_r32.filter(regex=("sim_Tc")),
        c=clrs,
        s=160,
        alpha=0.2,
    )

    tc, rhoc = calc_critical(df_r32_gaff)
    ax1.scatter(
        df_r32_gaff["rholiq_kgm3"],
        df_r32_gaff["T_K"],
        c='gray',
        s=120,
        alpha=0.7,
        label="GAFF",
        marker='s',
    )
    ax1.scatter(
        df_r32_gaff["rhovap_kgm3"],
        df_r32_gaff["T_K"],
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )
    ax1.scatter(
        rhoc,
        tc,
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )

    tc, rhoc = calc_critical(df_r32_raabe)
    ax1.scatter(
        df_r32_raabe["rholiq_kgm3"],
        df_r32_raabe["T_K"],
        c='#0989d9',
        s=140,
        alpha=0.7,
        label="Raabe",
        marker='^',
    )
    ax1.scatter(
        df_r32_raabe["rhovap_kgm3"],
        df_r32_raabe["T_K"],
        c='#0989d9',
        s=140,
        alpha=0.7,
        marker='^',
    )
    ax1.scatter(
        rhoc,
        tc,
        c='#0989d9',
        s=140,
        alpha=0.7,
        marker='^',
    )

    ax1.scatter(R32.expt_liq_density.values(),
                R32.expt_liq_density.keys(),
                color="black",
                marker="x",
                linewidths=2,
                s=200,
                label="Experiment  ")
    ax1.scatter(
        R32.expt_vap_density.values(),
        R32.expt_vap_density.keys(),
        color="black",
        marker="x",
        linewidths=2,
        s=200,
    )
    ax1.scatter(R32.expt_rhoc,
                R32.expt_Tc,
                color="black",
                marker="x",
                linewidths=2,
                s=200)

    ax1.set_xlim(-100, 1550)
    ax1.xaxis.set_major_locator(MultipleLocator(400))
    ax1.xaxis.set_minor_locator(AutoMinorLocator(4))

    ax1.set_ylim(220, 410)
    ax1.yaxis.set_major_locator(MultipleLocator(40))
    ax1.yaxis.set_minor_locator(AutoMinorLocator(4))

    ax1.tick_params("both",
                    direction="in",
                    which="both",
                    length=4,
                    labelsize=26,
                    pad=10)
    ax1.tick_params("both", which="major", length=8)
    ax1.xaxis.set_ticks_position("both")
    ax1.yaxis.set_ticks_position("both")

    ax1.set_ylabel("T (K)", fontsize=32, labelpad=10)
    ax1.set_xlabel(r"$\mathregular{\rho}$ (kg/m$\mathregular{^3}$)",
                   fontsize=32,
                   labelpad=15)
    #for axis in ['top','bottom','left','right']:
    #    ax.spines[axis].set_linewidth(2.0)

    clrs = seaborn.color_palette('bright', n_colors=len(df_r125))
    np.random.seed(11)
    np.random.shuffle(clrs)

    for temp in temps_r125:
        ax2.scatter(
            df_r125.filter(regex=(f"liq_density_{float(temp):.0f}K")),
            np.tile(temp, len(df_r125)),
            c=clrs,
            s=160,
            alpha=0.2,
        )
        ax2.scatter(
            df_r125.filter(regex=(f"vap_density_{float(temp):.0f}K")),
            np.tile(temp, len(df_r125)),
            c=clrs,
            s=160,
            alpha=0.2,
        )
    ax2.scatter(
        df_r125.filter(regex=("sim_rhoc")),
        df_r125.filter(regex=("sim_Tc")),
        c=clrs,
        s=160,
        alpha=0.2,
    )

    tc, rhoc = calc_critical(df_r125_gaff)
    ax2.scatter(
        df_r125_gaff["rholiq_kgm3"],
        df_r125_gaff["T_K"],
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )
    ax2.scatter(
        df_r125_gaff["rhovap_kgm3"],
        df_r125_gaff["T_K"],
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )
    ax2.scatter(
        rhoc,
        tc,
        c='gray',
        s=120,
        alpha=0.7,
        marker='s',
    )

    ax2.scatter(
        R125.expt_liq_density.values(),
        R125.expt_liq_density.keys(),
        color="black",
        marker="x",
        linewidths=2,
        s=200,
    )
    ax2.scatter(
        R125.expt_vap_density.values(),
        R125.expt_vap_density.keys(),
        color="black",
        marker="x",
        linewidths=2,
        s=200,
    )
    ax2.scatter(R125.expt_rhoc,
                R125.expt_Tc,
                color="black",
                marker="x",
                linewidths=2,
                s=200)

    ax2.set_xlim(-100, 1550)
    ax2.xaxis.set_major_locator(MultipleLocator(400))
    ax2.xaxis.set_minor_locator(AutoMinorLocator(4))

    ax2.set_ylim(220, 410)
    ax2.yaxis.set_major_locator(MultipleLocator(40))
    ax2.yaxis.set_minor_locator(AutoMinorLocator(4))

    ax2.tick_params("both",
                    direction="in",
                    which="both",
                    length=4,
                    labelsize=26,
                    pad=10)
    ax2.tick_params("both", which="major", length=8)
    ax2.xaxis.set_ticks_position("both")
    ax2.yaxis.set_ticks_position("both")

    ax2.set_ylabel("T (K)", fontsize=32, labelpad=10)
    ax2.set_xlabel(r"$\mathregular{\rho}$ (kg/m$\mathregular{^3}$)",
                   fontsize=32,
                   labelpad=15)
    for axis in ['top', 'bottom', 'left', 'right']:
        ax1.spines[axis].set_linewidth(2.0)
        ax2.spines[axis].set_linewidth(2.0)

    ax1.legend(loc="lower left",
               bbox_to_anchor=(0.28, 1.03),
               ncol=3,
               fontsize=22,
               handletextpad=0.1,
               markerscale=0.9,
               edgecolor="dimgrey")
    ax1.text(0.08, 0.82, "a", fontsize=40, transform=ax1.transAxes)
    ax1.text(0.5, 0.82, "HFC-32", fontsize=34, transform=ax1.transAxes)
    ax2.text(0.08, 0.82, "b", fontsize=40, transform=ax2.transAxes)
    ax2.text(0.4, 0.82, "HFC-125", fontsize=36, transform=ax2.transAxes)
    fig.subplots_adjust(bottom=0.2,
                        top=0.75,
                        left=0.15,
                        right=0.95,
                        wspace=0.55)

    fig.savefig("pdfs/fig3_results-vle.pdf")

    # Plot Pvap / Hvap
    fig, axs = plt.subplots(2, 2)

    clrs = seaborn.color_palette('bright', n_colors=len(df_r32))
    np.random.seed(11)
    np.random.shuffle(clrs)

    for temp in temps_r32:
        axs[0, 0].scatter(
            np.tile(temp, len(df_r32)),
            df_r32.filter(regex=(f"Pvap_{float(temp):.0f}K")),
            c=clrs,
            s=70,
            alpha=0.2,
        )
    axs[0, 0].scatter(
        df_r32_gaff["T_K"],
        df_r32_gaff["pvap_bar"],
        c='gray',
        s=50,
        alpha=0.7,
        label="GAFF",
        marker='s',
    )
    axs[0, 0].scatter(
        df_r32_raabe["T_K"],
        df_r32_raabe["pvap_bar"],
        c='#0989d9',
        s=70,
        alpha=0.7,
        label="Raabe",
        marker='^',
    )
    axs[0, 0].scatter(
        R32.expt_Pvap.keys(),
        R32.expt_Pvap.values(),
        color="black",
        marker="x",
        label="Experiment  ",
        s=80,
    )

    axs[0, 0].set_xlim(220, 330)
    axs[0, 0].xaxis.set_major_locator(MultipleLocator(40))
    axs[0, 0].xaxis.set_minor_locator(AutoMinorLocator(4))

    axs[0, 0].set_ylim(0, 40)
    axs[0, 0].yaxis.set_major_locator(MultipleLocator(10))
    axs[0, 0].yaxis.set_minor_locator(AutoMinorLocator(5))

    axs[0, 0].tick_params("both",
                          direction="in",
                          which="both",
                          length=2,
                          labelsize=12,
                          pad=5)
    axs[0, 0].tick_params("both", which="major", length=4)
    axs[0, 0].xaxis.set_ticks_position("both")
    axs[0, 0].yaxis.set_ticks_position("both")

    axs[0, 0].set_xlabel("T (K)", fontsize=16, labelpad=8)
    axs[0, 0].set_ylabel(r"$\mathregular{P_{vap}}$ (bar)",
                         fontsize=16,
                         labelpad=8)
    #for axis in ['top','bottom','left','right']:
    #    axs[0,0].spines[axis].set_linewidth(2.0)
    #    axs[0,1].spines[axis].set_linewidth(2.0)
    #    axs[1,0].spines[axis].set_linewidth(2.0)
    #    axs[1,1].spines[axis].set_linewidth(2.0)

    # Plot Enthalpy of Vaporization
    for temp in temps_r32:
        axs[1, 0].scatter(
            np.tile(temp, len(df_r32)),
            df_r32.filter(regex=(f"Hvap_{float(temp):.0f}K")),
            c=clrs,
            s=70,
            alpha=0.2,
        )
    axs[1, 0].scatter(
        df_r32_gaff["T_K"],
        df_r32_gaff["hvap_kJmol"] / R32.molecular_weight * 1000.0,
        c='gray',
        s=50,
        alpha=0.7,
        marker='s',
    )
    axs[1, 0].scatter(
        df_r32_raabe["T_K"],
        df_r32_raabe["hvap_kJmol"] / R32.molecular_weight * 1000.0,
        c='#0989d9',
        s=70,
        alpha=0.7,
        marker='^',
    )
    axs[1, 0].scatter(
        R32.expt_Hvap.keys(),
        R32.expt_Hvap.values(),
        color="black",
        marker="x",
        s=80,
    )

    axs[1, 0].set_xlim(220, 330)
    axs[1, 0].xaxis.set_major_locator(MultipleLocator(40))
    axs[1, 0].xaxis.set_minor_locator(AutoMinorLocator(4))

    axs[1, 0].set_ylim(-10, 410)
    axs[1, 0].yaxis.set_major_locator(MultipleLocator(100))
    axs[1, 0].yaxis.set_minor_locator(AutoMinorLocator(5))

    axs[1, 0].tick_params("both",
                          direction="in",
                          which="both",
                          length=2,
                          labelsize=12,
                          pad=5)
    axs[1, 0].tick_params("both", which="major", length=4)
    axs[1, 0].xaxis.set_ticks_position("both")
    axs[1, 0].yaxis.set_ticks_position("both")

    axs[1, 0].set_xlabel("T (K)", fontsize=16, labelpad=8)
    axs[1, 0].set_ylabel(r"$\mathregular{\Delta H_{vap}}$ (kJ/kg)",
                         fontsize=16,
                         labelpad=8)

    clrs = seaborn.color_palette('bright', n_colors=len(df_r125))
    np.random.seed(11)
    np.random.shuffle(clrs)

    for temp in temps_r125:
        axs[0, 1].scatter(
            np.tile(temp, len(df_r125)),
            df_r125.filter(regex=(f"Pvap_{float(temp):.0f}K")),
            c=clrs,
            s=70,
            alpha=0.2,
        )
    axs[0, 1].scatter(
        df_r125_gaff["T_K"],
        df_r125_gaff["pvap_bar"],
        c='gray',
        s=50,
        alpha=0.7,
        marker='s',
    )
    axs[0, 1].scatter(
        R125.expt_Pvap.keys(),
        R125.expt_Pvap.values(),
        color="black",
        marker="x",
        s=80,
    )

    axs[0, 1].set_xlim(220, 330)
    axs[0, 1].xaxis.set_major_locator(MultipleLocator(40))
    axs[0, 1].xaxis.set_minor_locator(AutoMinorLocator(4))

    axs[0, 1].set_ylim(0, 40)
    axs[0, 1].yaxis.set_major_locator(MultipleLocator(10))
    axs[0, 1].yaxis.set_minor_locator(AutoMinorLocator(5))

    axs[0, 1].tick_params("both",
                          direction="in",
                          which="both",
                          length=2,
                          labelsize=12,
                          pad=5)
    axs[0, 1].tick_params("both", which="major", length=4)
    axs[0, 1].xaxis.set_ticks_position("both")
    axs[0, 1].yaxis.set_ticks_position("both")

    axs[0, 1].set_xlabel("T (K)", fontsize=16, labelpad=8)
    axs[0, 1].set_ylabel(r"$\mathregular{P_{vap}}$ (bar)",
                         fontsize=16,
                         labelpad=8)

    # Plot Enthalpy of Vaporization
    for temp in temps_r125:
        axs[1, 1].scatter(
            np.tile(temp, len(df_r125)),
            df_r125.filter(regex=(f"Hvap_{float(temp):.0f}K")),
            c=clrs,
            s=70,
            alpha=0.2,
        )
    axs[1, 1].scatter(
        df_r125_gaff["T_K"],
        df_r125_gaff["hvap_kJmol"] / R125.molecular_weight * 1000.0,
        c='gray',
        s=50,
        alpha=0.7,
        marker='s',
    )
    axs[1, 1].scatter(
        R125.expt_Hvap.keys(),
        R125.expt_Hvap.values(),
        color="black",
        marker="x",
        s=80,
    )

    axs[1, 1].set_xlim(220, 330)
    axs[1, 1].xaxis.set_major_locator(MultipleLocator(40))
    axs[1, 1].xaxis.set_minor_locator(AutoMinorLocator(4))

    axs[1, 1].set_ylim(-10, 410)
    axs[1, 1].yaxis.set_major_locator(MultipleLocator(100))
    axs[1, 1].yaxis.set_minor_locator(AutoMinorLocator(5))

    axs[1, 1].tick_params("both",
                          direction="in",
                          which="both",
                          length=2,
                          labelsize=12,
                          pad=5)
    axs[1, 1].tick_params("both", which="major", length=4)
    axs[1, 1].xaxis.set_ticks_position("both")
    axs[1, 1].yaxis.set_ticks_position("both")

    axs[1, 1].set_xlabel("T (K)", fontsize=16, labelpad=8)
    axs[1, 1].set_ylabel(r"$\mathregular{\Delta H_{vap}}$ (kJ/kg)",
                         fontsize=16,
                         labelpad=8)

    axs[0, 0].text(0.08, 0.8, "a", fontsize=20, transform=axs[0, 0].transAxes)
    axs[0, 0].text(0.56,
                   0.08,
                   "HFC-32",
                   fontsize=16,
                   transform=axs[0, 0].transAxes)

    axs[0, 1].text(0.08, 0.8, "b", fontsize=20, transform=axs[0, 1].transAxes)
    axs[0, 1].text(0.5,
                   0.8,
                   "HFC-125",
                   fontsize=16,
                   transform=axs[0, 1].transAxes)

    axs[1, 0].text(0.08, 0.08, "c", fontsize=20, transform=axs[1, 0].transAxes)
    axs[1, 0].text(0.56,
                   0.08,
                   "HFC-32",
                   fontsize=16,
                   transform=axs[1, 0].transAxes)

    axs[1, 1].text(0.08, 0.8, "d", fontsize=20, transform=axs[1, 1].transAxes)
    axs[1, 1].text(0.5,
                   0.8,
                   "HFC-125",
                   fontsize=16,
                   transform=axs[1, 1].transAxes)

    axs[0, 0].legend(loc="lower left",
                     bbox_to_anchor=(0.25, 1.05),
                     ncol=3,
                     fontsize=12,
                     handletextpad=0.1,
                     markerscale=0.8,
                     edgecolor="dimgrey")

    fig.subplots_adjust(bottom=0.15,
                        top=0.88,
                        left=0.15,
                        right=0.95,
                        wspace=0.55,
                        hspace=0.5)
    fig.savefig("pdfs/fig3_result-si.pdf")
Esempio n. 17
0
    plt.tick_params(labelsize=25)
    plt.tick_params(which='both',
                    width=2,
                    top=True,
                    right=True,
                    direction='in')
    plt.tick_params(which='major', length=10)
    plt.tick_params(which='minor', length=6)  #, color='r’)
    plt.legend(scatterpoints=1,
               numpoints=1,
               loc=2,
               prop={'size': 32},
               ncol=1,
               handletextpad=0)
    from matplotlib.ticker import AutoMinorLocator
    ax.xaxis.set_minor_locator(AutoMinorLocator())
    ax.yaxis.set_minor_locator(AutoMinorLocator())
    cbar = f.colorbar(panel2[3], ax=obj, ticks=[])
    cbar.ax.tick_params(labelsize=30)
    plt.savefig('MM_SAM_zs_{0}.png'.format(zs))
    plt.show()

    #%%
    import matplotlib as mpl
    from matplotlib.ticker import AutoMinorLocator
    f, ax = plt.subplots(1,
                         2,
                         figsize=(12, 10),
                         gridspec_kw={'width_ratios': [7, 1]},
                         sharey=True)
    # f.suptitle(r"Offset VS M*, z={0}".format(zs), fontsize = 20)
        labeli = '{}:{}\n{}\n{}'.format(timei_formatted.hour,
                                        timei_formatted.minute, gdlat, glon)
        if second == 0:
            time_labels.append(labeli)
        else:
            None

    fig, axs = plt.subplots(2, 1, sharex=True, figsize=(10, 6.5))
    fig.subplots_adjust(hspace=0)

    axs[0].plot(times, diff_B_perp, linewidth=0.75, color='k')
    axs[0].tick_params(which='both', direction='inout')
    axs[0].tick_params(which='major', length=8, right=True)
    axs[0].tick_params(which='minor', length=4, right=True)
    axs[0].tick_params(which='major', labelsize=8)
    axs[1].yaxis.set_minor_locator(AutoMinorLocator())
    axs[0].autoscale(axis='x', tight=True)

    axs[1].plot(times, hor_ion_v, linewidth=0.75, color='k')
    axs[1].tick_params(which='both', direction='inout')
    axs[1].tick_params(which='major', length=8, right=True)
    axs[1].tick_params(which='minor', length=4, right=True)
    axs[1].tick_params(which='major', labelsize=8)
    axs[1].autoscale(axis='x', tight=True)

    axs[1].xaxis.set_major_locator(dates.MinuteLocator())
    axs[1].set_xticklabels(time_labels)
    # axs[1].xaxis.set_major_formatter(FormatStrFormatter('%d'))
    axs[1].xaxis.set_minor_locator(AutoMinorLocator())
    axs[1].yaxis.set_minor_locator(AutoMinorLocator())
    # ax1.yaxis.set_major_locator(MultipleLocator(20))
Esempio n. 19
0
def plot_thresholds(thresholds_data,
                    markersize=7,
                    title='Thresholds by Strategy and Attribute',
                    xlim=None,
                    ax=None,
                    figsize=None,
                    title_fontsize='large',
                    text_fontsize='medium'):
    """Plot thresholds by strategy and by attribute.

    Based on :func:`skplt.metrics.plot_roc`

    :param thresholds_data: Thresholds by attribute from the
                            function
                            :func:`~responsibly.interventions
                            .threshold.find_thresholds`.
    :type thresholds_data: dict
    :param int markersize: Marker size.
    :param str title: Title of the generated plot.
    :param tuple xlim: Set the data limits for the x-axis.
    :param ax: The axes upon which to plot the curve.
               If `None`, the plot is drawn on a new set of axes.
    :param tuple figsize: Tuple denoting figure size of the plot
                          e.g. (6, 6).
    :param title_fontsize: Matplotlib-style fontsizes.
                          Use e.g. 'small', 'medium', 'large'
                          or integer-values.
    :param text_fontsize: Matplotlib-style fontsizes.
                          Use e.g. 'small', 'medium', 'large'
                          or integer-values.
    :return: The axes on which the plot was drawn.
    :rtype: :class:`matplotlib.axes.Axes`
    """

    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=figsize)  # pylint: disable=unused-variable

    ax.set_title(title, fontsize=title_fontsize)

    # TODO: refactor!
    df = pd.DataFrame({
        _titlify(key): thresholds
        for key, (thresholds, *_) in thresholds_data.items()
        if key != 'separation'
    })
    melted_df = pd.melt(df, var_name='Strategy', value_name='Threshold')
    melted_df['Attribute'] = list(df.index) * len(df.columns)

    sns.stripplot(y='Strategy',
                  x='Threshold',
                  hue='Attribute',
                  data=melted_df,
                  jitter=False,
                  dodge=True,
                  size=markersize,
                  ax=ax)

    minor_locator = AutoMinorLocator(2)
    fig.gca().yaxis.set_minor_locator(minor_locator)
    ax.grid(which='minor')

    if xlim is not None:
        ax.set_xlim(*xlim)

    ax.set_xlabel('Threshold', fontsize=text_fontsize)
    ax.set_ylabel('Strategy', fontsize=text_fontsize)
    ax.tick_params(labelsize=text_fontsize)

    return ax
    def PlotShellIntensities(self,
                             df_peaks,
                             N_shells=10,
                             npeak_ratio=1,
                             normalized=True,
                             save_img=True):
        """
		Takes peak intensities and plots peak intensities by shell on log scale
		Returns dataframe of shells with int. int., d_min, d_max, n-peaks and D_half in each shell
		npeak_ratio: int, ratio of the N of peaks in highest to lowest res. shell
		npeak_ratio = 1 for equal number of peaks per shell
		"""
        df_shells = self.ShellIntensities(df_peaks,
                                          N_shells,
                                          npeak_ratio,
                                          normalized=normalized)
        plt.close('all')
        fig, ax = plt.subplots()
        plt.ion()

        # get the relevant intensity columns
        int_cols = [col for col in df_peaks.columns if col.startswith('I_')]
        int_cols.sort(key=lambda x: int(x.split('_')[1]))
        frame_numbers = [int(x.split('_')[1]) for x in int_cols]

        for shell_index in df_shells.index:
            d_min, d_max, half_dose = df_shells.loc[
                shell_index, ['d_min', 'd_max', 'D_half']]
            intensities = df_shells.loc[shell_index, int_cols]

            ax.plot(frame_numbers,intensities,marker='o',lw=2,label='%s - %s | %s' \
             %(toPrecision(d_max,3),toPrecision(d_min,3),toPrecision(half_dose,3)))

            #ax.scatter(frame_numbers,intensities,label='%s - %s | %s' \
            #	%(toPrecision(d_max,3),toPrecision(d_min,3),toPrecision(half_dose,3)))

        ax.set_yscale('log')
        leg = ax.legend(fontsize='x-small', markerscale=0)
        #leg = ax.legend(fontsize='x-small')
        leg.set_title('Resolution ($\mathrm{\AA)}$ | $D_{1/2}$',
                      prop={'size': 'x-small'})
        ax.set_xlabel('Frame Number', fontsize='x-large')
        ax.set_ylabel('MLFSOM Integrated Intensity\n(pixel value)',
                      fontsize='x-large')
        ax.tick_params(labelsize='large')
        ax.xaxis.set_minor_locator(AutoMinorLocator())
        ax.tick_params(axis='both', which='both', length=0)
        ax.grid(which='major', linewidth=0.4)
        ax.grid(which='minor', linewidth=0.2)
        ax.set_facecolor('0.95')
        for axis in ['top', 'bottom', 'left', 'right']:
            ax.spines[axis].set_visible(False)
        plt.tight_layout()
        if normalized:
            ymin = max(10**-2, df_shells[int_cols].min().min())
            ax.set_ylim(
                ymin=ymin
            )  # don't show noise caused by NaN intensities (reassigned to 0.1)
        if save_img:
            fig.savefig(join(self.dir_name, "fig_XYI_Shellintensities.png"),
                        dpi=200)
        plt.show()
        self.shells = df_shells
        return df_shells
Esempio n. 21
0
def gen_plots(archive_reports, log, outdir, full_archive):

    ordered_shas = [commit["git-sha"] for commit in log]
    ordered_reports = [
        archive_reports[sha] for sha in ordered_shas if sha in archive_reports
    ]

    # collect plot data
    plots = OrderedDict()
    for report in ordered_reports:
        for p in report["plots"]:
            if p["name"] not in plots.keys():
                plots[p["name"]] = {
                    "curves": OrderedDict(),
                    "title": p["title"],
                    "ylabel": p["ylabel"],
                }
        for pp in report["plotpoints"]:
            p = plots[pp["plot"]]
            if pp["name"] not in p["curves"].keys():
                p["curves"][pp["name"]] = {
                    "x": [],
                    "y": [],
                    "yerr": [],
                    "label": pp["label"],
                }
            c = p["curves"][pp["name"]]
            age = log.index[report["git-sha"]]
            c["x"].append(-age)
            c["y"].append(pp["y"])
            c["yerr"].append(pp["yerr"])

    # write raw data
    tags = sorted([(pname, cname) for pname, p in plots.items()
                   for cname in p["curves"].keys()])
    if tags:
        raw_output = "# %6s    %40s" % ("age", "commit")
        for pname, cname in tags:
            raw_output += "   %18s   %22s" % (
                pname + "/" + cname,
                pname + "/" + cname + "_err",
            )
        raw_output += "\n"
        for report in reversed(ordered_reports):
            age = log.index[report["git-sha"]]
            raw_output += "%8d    %40s" % (-age, report["git-sha"])
            for pname, cname in tags:
                pp = [
                    pp for pp in report["plotpoints"]
                    if (pp["plot"] == pname and pp["name"] == cname)
                ]
                if len(pp) > 1:
                    print("Warning: Found redundant plot points.")
                if pp:
                    raw_output += "   %18f   %22f" % (pp[-1]["y"],
                                                      pp[-1]["yerr"])
                else:
                    raw_output += "   %18s   %22s" % ("?", "?")
            raw_output += "\n"
        write_file(outdir + "plot_data.txt", raw_output)

    # create png images
    if full_archive:
        fig_ext = "_full.png"
        max_age = max([-1] +
                      [log.index[sha] for sha in archive_reports.keys()])
    else:
        fig_ext = ".png"
        max_age = 100

    for pname, p in plots.items():
        print("Working on plot: " + pname)
        fig = plt.figure(figsize=(12, 4))
        fig.subplots_adjust(bottom=0.18, left=0.06, right=0.70)
        fig.suptitle(p["title"], fontsize=14, fontweight="bold", x=0.4)
        ax = fig.add_subplot(111)
        ax.set_xlabel("Commit Age")
        ax.set_ylabel(p["ylabel"])
        markers = itertools.cycle("os>^*")
        for cname in p["curves"].keys():
            c = p["curves"][cname]
            if full_archive:
                ax.plot(c["x"], c["y"], label=c["label"],
                        linewidth=2)  # less crowded
            else:
                ax.errorbar(
                    c["x"],
                    c["y"],
                    yerr=c["yerr"],
                    label=c["label"],
                    marker=next(markers),
                    linewidth=2,
                    markersize=6,
                )
        ax.set_xlim(-max_age - 1, 0)
        ax.xaxis.set_minor_locator(AutoMinorLocator())
        ax.legend(
            bbox_to_anchor=(1.01, 1),
            loc="upper left",
            numpoints=1,
            fancybox=True,
            shadow=True,
            borderaxespad=0.0,
        )
        visibles = [[y for x, y in zip(c["x"], c["y"]) if x >= -max_age]
                    for c in p["curves"].values()]  # visible y-values
        visibles = [ys for ys in visibles
                    if ys]  # remove completely invisible curves
        if not visibles:
            print("Warning: Found no visible plot curve.")
        else:
            ymin = min([min(ys)
                        for ys in visibles])  # lowest point from lowest curve
            ymax = max([max(ys) for ys in visibles
                        ])  # highest point from highest curve
            if full_archive:
                ax.set_ylim(0.98 * ymin, 1.02 * ymax)
            else:
                ymax2 = max([min(ys) for ys in visibles
                             ])  # lowest point from highest curve
                ax.set_ylim(0.98 * ymin,
                            min(1.02 * ymax,
                                1.3 * ymax2))  # protect against outlayers
        fig.savefig(outdir + pname + fig_ext)
        plt.close(fig)

    # write html output
    html_output = ""
    for pname in sorted(plots.keys()):
        html_output += '<a href="plot_data.txt"><img src="%s" alt="%s"></a>\n' % (
            pname + fig_ext,
            plots[pname]["title"],
        )
    return html_output
W4mag = VHzQ['W4mag']

##  Making the plot(s)
plt.rcParams.update({'font.size': 14})
#matplotlib.rc('text', usetex=True)

## https://matplotlib.org/examples/pylab_examples/subplots_demo.html
## Will scale this up at some point to a full-page 3x2
fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(nrows=3,
                                                         ncols=2,
                                                         figsize=(12, 16),
                                                         dpi=80,
                                                         facecolor='w',
                                                         edgecolor='k')

minorLocator = AutoMinorLocator()

#table['SpT-opt-n'][0:100]

labelsize = 16
tickwidth = 2.0
majorticklength = 12
minorticklength = 6
ticklabelsize = labelsize

ls = 'solid'
lw = 1.0
ms_clrsize = ((redshift - 3.9)**5.5)
ms_large = 360.
ms = 120.
ms_small = 14.
Esempio n. 23
0
if (args.xrotate):
    plt.xticks(rotation=args.xrotate)

if args.ylabel:
    ax.set_ylabel(args.ylabel)

if args.ylim:
    if (len(args.ylim) == 1):
        ax.set_ylim(args.ylim[0])
    elif (len(args.ylim) == 2):
        ax.set_ylim(args.ylim[0], args.ylim[1])
    else:
        sys.exit('provide one or two args to --ylim')

ax.xaxis.set_major_locator(MultipleLocator(10))
ax.xaxis.set_minor_locator(AutoMinorLocator(5))
ax.xaxis.grid(True, which='major')
ax.xaxis.grid(True, which='minor', alpha=0.5)

# secondary axis handling
if df2 is not None:
    for cidx in range(1, len(df2.columns)):
        fullargs = populate_args(cidx, kwargs, True)
        vprint("(secondary) kwargs for col {}: {}".format(cidx, fullargs))
        ax2 = df2.plot.line(x=0,
                            secondary_y=True,
                            ax=ax,
                            grid=True,
                            **fullargs)
        if (args.ylabel2):
            ax2.set_ylabel(args.ylabel2)
Esempio n. 24
0
#group2
gaussian = (3.34, 2.68, 4.32)

label = ('(a) baseline', '(b)', '(c)', '(d)')

fig, ax = plt.subplots()

index = np.arange(4)
index1 = np.arange(1)
index2 = np.arange(3) + 1
bar_width = 0.25
plt.ylim(0, 5)
plt.axhline(y=1, color='grey', linewidth=0.5, linestyle='--')

minorLocator = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minorLocator)
plt.tick_params(which='minor', length=4)
plt.tick_params(which='major', bottom=False, top=False)

rGCuda = ax.bar(index1 - 1.15 * bar_width,
                2.76,
                bar_width,
                alpha=0.8,
                color='black')  #, hatch='//')
rGOpencl = ax.bar(index1, 1.65, bar_width, alpha=0.4,
                  color='black')  #hatch='\\')
rBfsOpencl = ax.bar(index1 + 1.15 * bar_width,
                    1,
                    bar_width,
                    alpha=0.6,
Esempio n. 25
0
    def get_plot(self,
                 width=None,
                 height=None,
                 xmin=0.,
                 xmax=None,
                 ymin=0,
                 ymax=None,
                 colours=None,
                 dpi=400,
                 plt=None,
                 fonts=None,
                 style=None,
                 no_base_style=False):
        """Get a :obj:`matplotlib.pyplot` object of the optical spectra.

        Args:
            width (:obj:`float`, optional): The width of the plot.
            height (:obj:`float`, optional): The height of the plot.
            xmin (:obj:`float`, optional): The minimum energy on the x-axis.
            xmax (:obj:`float`, optional): The maximum energy on the x-axis.
            ymin (:obj:`float`, optional): The minimum absorption intensity on
                the y-axis.
            ymax (:obj:`float`, optional): The maximum absorption intensity on
                the y-axis.
            colours (:obj:`list`, optional): A :obj:`list` of colours to use in
                the plot. The colours can be specified as a hex code, set of
                rgb values, or any other format supported by matplotlib.
            dpi (:obj:`int`, optional): The dots-per-inch (pixel density) for
                the image.
            plt (:obj:`matplotlib.pyplot`, optional): A
                :obj:`matplotlib.pyplot` object to use for plotting.
            fonts (:obj:`list`, optional): Fonts to use in the plot. Can be a
                a single font, specified as a :obj:`str`, or several fonts,
                specified as a :obj:`list` of :obj:`str`.
            style (:obj:`list`, :obj:`str`, or :obj:`dict`): Any matplotlib
                style specifications, to be composed on top of Sumo base
                style.
            no_base_style (:obj:`bool`, optional): Prevent use of sumo base
                style. This can make alternative styles behave more
                predictably.

        Returns:
            :obj:`matplotlib.pyplot`: The plot of optical spectra.
        """
        n_plots = len(self._spec_data)
        plt = pretty_subplot(n_plots,
                             1,
                             sharex=True,
                             sharey=False,
                             width=width,
                             height=height,
                             dpi=dpi,
                             plt=plt)
        fig = plt.gcf()

        optics_colours = rcParams['axes.prop_cycle'].by_key()['color']
        if colours is not None:
            optics_colours = colours + optics_colours

        standard_ylabels = {
            'absorption': r'Absorption (cm$^\mathregular{-1}$)',
            'loss': r'Energy-loss',
            'eps_real': r'Re($\epsilon$)',
            'eps_imag': r'Im($\epsilon$)',
            'n_real': r'Re(n)',
            'n_imag': r'Im(n)'
        }

        if ymax is None:
            ymax_series = [None] * n_plots
        elif isinstance(ymax, float) or isinstance(ymax, int):
            ymax_series = [ymax] * n_plots
        elif not isinstance(ymax, list):
            raise ValueError()
        else:
            ymax_series = ymax

        if ymin is None:
            ymin_series = [None] * n_plots
        elif isinstance(ymin, float) or isinstance(ymin, int):
            ymin_series = [ymin] * n_plots
        elif not isinstance(ymin, list):
            raise ValueError()
        else:
            ymin_series = ymin

        for i, (spectrum_key, data), ymin, ymax in zip(range(n_plots),
                                                       self._spec_data.items(),
                                                       ymin_series,
                                                       ymax_series):
            ax = fig.axes[i]
            _plot_spectrum(data, self._label, self._band_gap, ax,
                           optics_colours)

            xmax = xmax if xmax else self._xmax
            ax.set_xlim(xmin, xmax)

            if ymin is None and spectrum_key in ('absorption', 'loss',
                                                 'eps_imag', 'n_imag'):
                ymin = 0
            elif ymin is None:
                ymin = ax.get_ylim()[0]

            if ymax is None and spectrum_key in ('absorption', ):
                ymax = 1e5
            elif ymax is None:
                ymax = ax.get_ylim()[1]

            ax.set_ylim(ymin, ymax)

            if spectrum_key == 'absorption':
                font = findfont(FontProperties(family=['sans-serif']))
                if 'Whitney' in font:
                    times_sign = 'x'
                else:
                    times_sign = r'\times'
                ax.yaxis.set_major_formatter(
                    FuncFormatter(curry_power_tick(times_sign=times_sign)))

            ax.yaxis.set_major_locator(MaxNLocator(5))
            ax.xaxis.set_major_locator(MaxNLocator(3))
            ax.yaxis.set_minor_locator(AutoMinorLocator(2))
            ax.xaxis.set_minor_locator(AutoMinorLocator(2))

            ax.set_ylabel(standard_ylabels.get(spectrum_key, spectrum_key))

            if i == 0:
                if (not np.all(np.array(self._label) == '') or len(
                        np.array(next(iter(
                            self._spec_data.items()))[1][0][1]).shape) > 1):
                    ax.legend(loc='best', frameon=False, ncol=1)

        ax.set_xlabel('Energy (eV)')

        # If only one plot, fix aspect ratio to match canvas
        if len(self._spec_data) == 1:
            x0, x1 = ax.get_xlim()
            y0, y1 = ax.get_ylim()
            if width is None:
                width = rcParams['figure.figsize'][0]
            if height is None:
                height = rcParams['figure.figsize'][1]
            ax.set_aspect((height / width) * ((x1 - x0) / (y1 - y0)))

        # Otherwise, rely only on tight_layout and hope for the best
        plt.tight_layout()
        return plt
Esempio n. 26
0
for cap in boxes1['caps']:
    cap.set(color='#004f82', linewidth=1)
for flier in boxes1['fliers']:
    flier.set(color='#004f82')
for median in boxes1['medians']:
    median.set(color='#004f82', linewidth=2)

ax.set_xlim([0, 141])
ax.set_xlabel('Years', fontweight='bold')
ax.yaxis.set_tick_params(left='off',
                         right='off',
                         labelright='on',
                         labelleft='off',
                         pad=7)
xmajorLocator = MultipleLocator(20)
xminorLocator = AutoMinorLocator(2)
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_minor_locator(xminorLocator)
ax.xaxis.set_tick_params(which='major', width=2)

ax2 = ax.twiny()
# ToE 1 1%CO2 vs. PiControl boxes
boxes2 = ax2.boxplot(data1,
                     vert=0,
                     positions=ind + width,
                     widths=width,
                     whis=0)
for box in boxes2['boxes']:
    box.set(color='#4c9ccf', linewidth=2)
for whisker in boxes2['whiskers']:
    whisker.set(color='#4c9ccf', linestyle='-', linewidth=1)
Esempio n. 27
0
def plot_amm_specfit(sp,
                     stack,
                     pix,
                     n_model=1,
                     outname='specfit',
                     cold=False,
                     kind='map',
                     zoom=False,
                     dv=31):
    assert kind in ('map', 'bestfit')
    lon_pix, lat_pix = pix
    group = sp.store.hdf[f'/pix/{lon_pix}/{lat_pix}/{n_model}']
    params = group[f'{kind}_params'][...]
    print(params)
    obs_spec = stack.get_arrays(*pix)
    xarrs = get_amm_psk_xarrs(stack)
    syn_spec = [
        SyntheticSpectrum(x, params, trans_id=i + 1, cold=cold)
        for i, x in enumerate(xarrs)
    ]
    fig, axes = plt.subplots(nrows=2,
                             sharex=True,
                             sharey=True,
                             figsize=(4, 3.5))
    for data, xarr, model, ax in zip(obs_spec, xarrs, syn_spec, axes):
        varr = model.varr
        ax.fill_between(varr,
                        data,
                        np.zeros_like(data),
                        color='yellow',
                        edgecolor='none',
                        alpha=0.5)
        ax.plot(varr, data, 'k-', linewidth=0.7, drawstyle='steps-mid')
        # FIXME replace components with `models.ammonia` versus pyspeckit
        # (slight difference due to updated constants)
        ax.plot(varr,
                model.components.T,
                '-',
                color='magenta',
                linewidth=1.0,
                alpha=0.5)
        ax.plot(varr,
                model.mod_spec,
                '-',
                color='red',
                linewidth=1.0,
                drawstyle='steps-mid')
        ax.set_xlim(varr.value.min(), varr.value.max())
    if zoom:
        vcen = ((varr[0] + varr[-1]) / 2).value
        axes[0].set_xlim(vcen - dv, vcen + dv)
        axes[1].set_xlim(vcen - dv, vcen + dv)
    ymin = 1.1 * obs_spec[0].min()
    ymax = 1.1 * obs_spec[0].max()
    axes[0].set_ylim(ymin, ymax)
    axes[1].set_xlabel(r'$v_\mathrm{lsr} \ [\mathrm{km\, s^{-1}}]$')
    axes[1].set_ylabel(r'$T_\mathrm{mb} \ [\mathrm{K}]$')
    axes[0].annotate(r'$\mathrm{NH_3}\, (1,1)$', (0.03, 0.80),
                     xycoords='axes fraction')
    axes[1].annotate(r'$\mathrm{NH_3}\, (2,2)$', (0.03, 0.80),
                     xycoords='axes fraction')
    for ax in axes:
        ax.xaxis.set_minor_locator(AutoMinorLocator(5))
        ax.xaxis.set_tick_params(which='minor', bottom='on')
        ax.yaxis.set_minor_locator(AutoMinorLocator(5))
        ax.yaxis.set_tick_params(which='minor', left='on')
    plt.tight_layout(h_pad=0.5)
    sp.save(f'{outname}_{lon_pix}_{lat_pix}_{n_model}')
Esempio n. 28
0
     p_hist, p_bins = np.histogram(p, bins=bins)
 else:
     D_hist, D_bins = np.histogram(D, bins='auto')
     p_hist, p_bins = np.histogram(p, bins='auto')
 D_hist_sim, _ = np.histogram(D_sim, bins=D_bins)
 p_hist_sim, _ = np.histogram(p_sim, bins=p_bins)
 hists = [[D_hist, D_hist_sim], [p_hist, p_hist_sim]]
 bins = [D_bins, p_bins]
 fig, ax = plt.subplots(figsize=(14, 8), nrows=2, ncols=2)
 fig.suptitle('%i ks test, $\sigma$=%i' % (obs, sig_thresh))
 kwargs = {'cmap': cm.coolwarm,
           'xlabel': 'Frequency (Mhz)',
           'cbar_label': '$\sigma$',
           'xticks': xticks,
           'xticklabels': xticklabels,
           'xminors': AutoMinorLocator(4),
           'mask_color': 'black'}
 for i in range(4):
     args = (fig, ax[i / 2][i % 2], MS[:, 0, :, i])
     kwargs['title'] = pols[i]
     pl.image_plot(*args, **kwargs)
     fig.savefig('%s/%i_KS_%i.png' % (outpath, obs, sig_thresh))
 plt.close(fig)
 titles = ['KS Statistic Histogram', 'KS P-Value Histogram']
 tags = ['KS_Stat', 'KS_P']
 xlabels = ['$D_n$', 'p']
 for hist, bin, title, tag, xlabel in zip(hists, bins, titles, tags, xlabels):
     fig, ax = plt.subplots(figsize=(14, 8))
     args = (fig, ax, bin, hist)
     kwargs = {'xlog': True,
               'ylog': True,
Esempio n. 29
0
def plotPolicy(
    X, Y, U, V, M, w, h, **kwargs
):  #show and save default to false. title, colorbar-label, filename
    plt.clf()

    mask = np.logical_or(U != 0, V != 0)
    X = X[mask]
    Y = Y[mask]
    U = U[mask]
    V = V[mask]

    fig1, ax1 = plt.subplots()

    if 'title' in kwargs:
        ax1.set_title(kwargs['title'])

    # Make the arrows
    Q = ax1.quiver(X,
                   Y,
                   U,
                   V,
                   M,
                   units='x',
                   pivot='middle',
                   width=0.05,
                   cmap="autumn_r",
                   scale=1 / 0.8)

    # Shade and label goal cell
    ax1.text(w - 1 + 0.2, h - 1 + 0.4, 'Goal', color="g",
             fontsize=15)  #, transform=ax1.transAxes)
    fill([w - 1, w, w, w - 1], [h - 1, h - 1, h, h],
         'g',
         alpha=0.2,
         edgecolor='g')

    if "cbarlbl" in kwargs:
        # Create colorbar
        cbar = ax1.figure.colorbar(Q, ax=ax1)  #, **cbar_kw)

        t = kwargs["cbarlbl"]  # label colorbar
        cbar.ax.set_ylabel(t, rotation=-90, va="bottom")

    # make grid lines on center
    plt.xticks([0.5 + i for i in range(w)], [i for i in range(w)])
    plt.yticks([0.5 + i for i in range(h)], [i for i in range(h)])
    plt.xlim(0, w)
    plt.ylim(0, h)
    # make grid
    minor_locator1 = AutoMinorLocator(2)
    minor_locator2 = FixedLocator([j for j in range(h)])
    plt.gca().xaxis.set_minor_locator(minor_locator1)
    plt.gca().yaxis.set_minor_locator(minor_locator2)
    plt.grid(which='minor')

    plt.xlabel("cell x coord.")
    plt.ylabel("cell y coord.")
    # plt.tight_layout()

    if 'filename' in kwargs:
        plt.savefig(kwargs['filename'], dpi=200)
    if 'show' in kwargs:
        if kwargs['show']:
            plt.show()
Esempio n. 30
0
    #plt.plot(epsplot, ai(epsplot, *popt), label="fit")
    #print(popt)
ax.tick_params(left=True,
               right=True,
               bottom=True,
               top=True,
               which='major',
               length=10)
ax.tick_params(right=True, direction='in', which='both')
ax.tick_params(left=True,
               right=True,
               bottom=True,
               top=True,
               which='minor',
               length=5)
minor_locator_x = AutoMinorLocator(2)
minor_locator_y = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minor_locator_x)
ax.yaxis.set_minor_locator(minor_locator_y)
#ax.set_xticklabels(["$-1$","$-0,8$","$-0.6$","$-0.4$",
#                    "$-0.2$","$0$",r"$\epsilon_\theta$"])

minor_locator_x = AutoMinorLocator(2)
#minor_locator_y = AutoMinorLocator(2)
ax.xaxis.set_minor_locator(minor_locator_x)
#ax.yaxis.set_minor_locator(minor_locator_y)
#plt.xticks(plt.yticks()[0][::2]) # jeden zweiten Tick löschen
plt.xticks([0, 2, 4, 6, 8])
ax.set_xlim(0, 8)
ax.set_ylim(0, 1200)
plt.subplots_adjust(left=0.12, right=0.98, top=0.98, bottom=0.09)