Exemplo n.º 1
0
 def set_default_locators_and_formatters(self, axis):
     # docstring inherited
     axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
     axis.set_major_formatter(LogFormatterSciNotation(self.base))
     axis.set_minor_locator(SymmetricalLogLocator(self.get_transform(),
                                                  self.subs))
     axis.set_minor_formatter(NullFormatter())
Exemplo n.º 2
0
    def set_default_locators_and_formatters(self, axis):
        # Copy of Symmetric LogScale version of this function

        axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
        axis.set_major_formatter(LogFormatterMathtext(self.base))
        axis.set_minor_locator(
            SymmetricalLogLocator(self.get_transform(), self.subs))
        axis.set_minor_formatter(NullFormatter())
Exemplo n.º 3
0
 def set_default_locators_and_formatters(self, axis):
     """
     Set the locators and formatters to specialized versions for
     symmetrical log scaling.
     """
     axis.set_major_locator(SymmetricalLogLocator(self.get_transform()))
     axis.set_major_formatter(LogFormatterSciNotation(self.base))
     axis.set_minor_locator(
         SymmetricalLogLocator(self.get_transform(), self.subs))
     axis.set_minor_formatter(NullFormatter())
Exemplo n.º 4
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([])
Exemplo n.º 5
0
 def plot_together(self,
                   fname,
                   plot_columns,
                   valid_column='valid',
                   dir_proc='.'):
     groupby_df = self.data.groupby(self.data[valid_column])
     try:
         group_valid = groupby_df.get_group(True)
     except KeyError:
         some_valid = False
     else:
         some_valid = True
     try:
         group_invalid = groupby_df.get_group(False)
     except KeyError:
         some_invalid = False
     else:
         some_invalid = True
     for col in plot_columns:
         fig, ax = plt.subplots()
         if some_valid:
             nmeas_valid = group_valid['meas'].to_numpy()
             ax.plot(nmeas_valid,
                     group_valid[col].to_numpy(),
                     'o',
                     color='b',
                     markersize=4)
         if some_invalid:
             nmeas_invalid = group_invalid['meas'].to_numpy()
             ax.plot(nmeas_invalid,
                     group_invalid[col].to_numpy(),
                     'o',
                     color='r',
                     markersize=4)
         scale, vstdmedian, vskewness = find_best_yscale(self.data[col])
         if scale == 'symlog':
             threshold = find_threshold_minnonzero(self.data[col])
             plt.minorticks_on()
             ax.set_yscale('symlog',
                           linscale=0.2,
                           linthresh=threshold,
                           base=10)
             ax.yaxis.set_major_locator(
                 SymmetricalLogLocator(base=10, linthresh=threshold))
             ax.yaxis.set_minor_locator(MinorSymLogLocator(threshold))
         else:
             ax.set_yscale(scale)
             plt.minorticks_on()
         ax.grid(which='both', axis='both')
         plt.ylabel(col)
         plt.xlabel('measurement num')
         plt.tight_layout()
         os.makedirs(dir_proc, exist_ok=True)
         fig_fname = fname.replace('.Data', '_') + col + '.png'
         fig_dirfname = os.path.join(dir_proc, fig_fname)
         plt.savefig(fig_dirfname, dpi=100)
         plt.close()
Exemplo n.º 6
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
Exemplo n.º 7
0
def __decorate_axis(axis,
                    ax_type,
                    key='C:maj',
                    Sa=None,
                    mela=None,
                    thaat=None):
    """Configure axis tickers, locators, and labels"""
    if ax_type == 'time':
        axis.set_major_formatter(TimeFormatter(unit=None, lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Time')
    elif ax_type in ['mel', 'log']:
        axis.set_major_formatter(ScalarFormatter())
        axis.set_major_locator(SymmetricalLogLocator(axis.get_transform()))
        axis.set_label_text('Hz')
Exemplo n.º 8
0
def plot_ds(fdir, field="x_velocity"):

    # Load the data
    ds = yt.load(fdir, unit_system="mks")

    # Setup
    L = (ds.domain_right_edge - ds.domain_left_edge).d
    width = L[0]
    res = 512
    zlocs = np.array([0.0525, 0.0775, 0.1025, 0.1275, 0.1525])
    fname = "slices.pdf"

    with PdfPages(fname) as pdf:
        plt.close("all")
        plt.rc("text", usetex=True)
        linthresh = 1e-3

        # Get a slice in x
        slc = yt.SlicePlot(ds, "x", fields=[field])
        frb = slc.data_source.to_frb(width, res)
        x_slc = np.array(frb[field])

        fig0 = plt.figure(0)
        ax0 = fig0.add_subplot(111)
        im = ax0.imshow(
            x_slc,
            origin="lower",
            extent=[
                ds.domain_left_edge.d[0],
                ds.domain_right_edge.d[0],
                ds.domain_left_edge.d[2],
                ds.domain_right_edge.d[2],
            ],
            aspect="equal",
            cmap="Spectral_r",
            norm=colors.SymLogNorm(linthresh=linthresh,
                                   linscale=0.5,
                                   vmin=x_slc.min(),
                                   vmax=x_slc.max()),
        )
        cbar = plt.colorbar(im,
                            ax=ax0,
                            ticks=SymmetricalLogLocator(linthresh=linthresh,
                                                        base=10))
        cbar.ax.set_title(r"$u$")

        for zloc in zlocs:
            ax0.plot(
                [ds.domain_left_edge.d[0], ds.domain_right_edge.d[0]],
                [zloc, zloc],
                color="w",
                lw=1,
                ls="--",
            )

        ax0.set_xlabel(r"$y~[\mathrm{m}]$", fontsize=22, fontweight="bold")
        ax0.set_ylabel(r"$z~[\mathrm{m}]$", fontsize=22, fontweight="bold")
        plt.setp(ax0.get_xmajorticklabels(), fontsize=18)
        plt.setp(ax0.get_ymajorticklabels(), fontsize=18)
        fig0.subplots_adjust(bottom=0.15)
        fig0.subplots_adjust(left=0.17)
        pdf.savefig(dpi=300)

        # Get slices in z
        for k, zloc in enumerate(zlocs):
            slc = yt.SlicePlot(ds, "z", fields=[field], center=[0, 0, zloc])
            frb = slc.data_source.to_frb(width, res)
            z_slc = np.array(frb[field])

            fig0 = plt.figure(k + 1)
            ax0 = fig0.add_subplot(111)
            im = ax0.imshow(
                z_slc,
                origin="lower",
                extent=[
                    ds.domain_left_edge.d[0],
                    ds.domain_right_edge.d[0],
                    ds.domain_left_edge.d[1],
                    ds.domain_right_edge.d[1],
                ],
                aspect="equal",
                cmap="Spectral_r",
                norm=colors.SymLogNorm(
                    linthresh=linthresh,
                    linscale=0.5,
                    vmin=x_slc.min(),
                    vmax=x_slc.max(),
                ),
            )
            cbar = plt.colorbar(im,
                                ax=ax0,
                                ticks=SymmetricalLogLocator(
                                    linthresh=linthresh, base=10))
            cbar.ax.set_title(r"$u$")

            ax0.set_xlabel(r"$x~[\mathrm{m}]$", fontsize=22, fontweight="bold")
            ax0.set_ylabel(r"$y~[\mathrm{m}]$", fontsize=22, fontweight="bold")
            plt.setp(ax0.get_xmajorticklabels(), fontsize=18)
            plt.setp(ax0.get_ymajorticklabels(), fontsize=18)
            fig0.subplots_adjust(bottom=0.15)
            fig0.subplots_adjust(left=0.17)
            pdf.savefig(dpi=300)
Exemplo n.º 9
0
def __decorate_axis(axis,
                    ax_type,
                    key="C:maj",
                    Sa=None,
                    mela=None,
                    thaat=None):
    """Configure axis tickers, locators, and labels"""

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

    elif ax_type == "chroma":
        axis.set_major_formatter(ChromaFormatter(key=key))
        degrees = core.key_to_degrees(key)
        axis.set_major_locator(
            FixedLocator(0.5 +
                         np.add.outer(12 * np.arange(10), degrees).ravel()))
        axis.set_label_text("Pitch class")

    elif ax_type == "chroma_h":
        if Sa is None:
            Sa = 0
        axis.set_major_formatter(ChromaSvaraFormatter(Sa=Sa))
        if thaat is None:
            # If no thaat is given, show all svara
            degrees = np.arange(12)
        else:
            degrees = core.thaat_to_degrees(thaat)
        # Rotate degrees relative to Sa
        degrees = np.mod(degrees + Sa, 12)
        axis.set_major_locator(
            FixedLocator(0.5 +
                         np.add.outer(12 * np.arange(10), degrees).ravel()))
        axis.set_label_text("Svara")

    elif ax_type == "chroma_c":
        if Sa is None:
            Sa = 0
        axis.set_major_formatter(ChromaSvaraFormatter(Sa=Sa, mela=mela))
        degrees = core.mela_to_degrees(mela)
        # Rotate degrees relative to Sa
        degrees = np.mod(degrees + Sa, 12)
        axis.set_major_locator(
            FixedLocator(0.5 +
                         np.add.outer(12 * np.arange(10), degrees).ravel()))
        axis.set_label_text("Svara")

    elif ax_type in ["tempo", "fourier_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(unit=None, lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text("Time")

    elif ax_type == "s":
        axis.set_major_formatter(TimeFormatter(unit="s", lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text("Time (s)")

    elif ax_type == "ms":
        axis.set_major_formatter(TimeFormatter(unit="ms", lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text("Time (ms)")

    elif ax_type == "lag":
        axis.set_major_formatter(TimeFormatter(unit=None, lag=True))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text("Lag")

    elif ax_type == "lag_s":
        axis.set_major_formatter(TimeFormatter(unit="s", lag=True))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text("Lag (s)")

    elif ax_type == "lag_ms":
        axis.set_major_formatter(TimeFormatter(unit="ms", lag=True))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text("Lag (ms)")

    elif ax_type == "cqt_note":
        axis.set_major_formatter(NoteFormatter(key=key))
        # Where is C1 relative to 2**k hz?
        log_C1 = np.log2(core.note_to_hz("C1"))
        C_offset = 2.0**(log_C1 - np.floor(log_C1))
        axis.set_major_locator(LogLocator(base=2.0, subs=(C_offset, )))
        axis.set_minor_formatter(NoteFormatter(key=key, major=False))
        axis.set_minor_locator(
            LogLocator(base=2.0,
                       subs=C_offset * 2.0**(np.arange(1, 12) / 12.0)))
        axis.set_label_text("Note")

    elif ax_type == "cqt_svara":
        axis.set_major_formatter(SvaraFormatter(Sa=Sa, mela=mela))
        # Find the offset of Sa relative to 2**k Hz
        sa_offset = 2.0**(np.log2(Sa) - np.floor(np.log2(Sa)))

        axis.set_major_locator(LogLocator(base=2.0, subs=(sa_offset, )))
        axis.set_minor_formatter(SvaraFormatter(Sa=Sa, mela=mela, major=False))
        axis.set_minor_locator(
            LogLocator(base=2.0,
                       subs=sa_offset * 2.0**(np.arange(1, 12) / 12.0)))
        axis.set_label_text("Svara")

    elif ax_type in ["cqt_hz"]:
        axis.set_major_formatter(LogHzFormatter())
        log_C1 = np.log2(core.note_to_hz("C1"))
        C_offset = 2.0**(log_C1 - np.floor(log_C1))
        axis.set_major_locator(LogLocator(base=2.0, subs=(C_offset, )))
        axis.set_major_locator(LogLocator(base=2.0))
        axis.set_minor_formatter(LogHzFormatter(major=False))
        axis.set_minor_locator(
            LogLocator(base=2.0,
                       subs=C_offset * 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([])

    else:
        raise ParameterError("Unsupported axis type: {}".format(ax_type))
Exemplo n.º 10
0
def __decorate_axis(axis, ax_type):
    '''Configure axis tickers, locators, and labels'''

    if ax_type == 'tonnetz':
        axis.set_major_formatter(TonnetzFormatter())
        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 in ['tempo', 'fourier_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(unit=None, lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Time')

    elif ax_type == 's':
        axis.set_major_formatter(TimeFormatter(unit='s', lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Time (s)')

    elif ax_type == 'ms':
        axis.set_major_formatter(TimeFormatter(unit='ms', lag=False))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Time (ms)')

    elif ax_type == 'lag':
        axis.set_major_formatter(TimeFormatter(unit=None, lag=True))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Lag')

    elif ax_type == 'lag_s':
        axis.set_major_formatter(TimeFormatter(unit='s', lag=True))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Lag (s)')

    elif ax_type == 'lag_ms':
        axis.set_major_formatter(TimeFormatter(unit='ms', lag=True))
        axis.set_major_locator(
            MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
        axis.set_label_text('Lag (ms)')

    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(LogHzFormatter())
        axis.set_major_locator(LogLocator(base=2.0))
        axis.set_minor_formatter(LogHzFormatter(major=False))
        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([])

    else:
        raise ParameterError('Unsupported axis type: {}'.format(ax_type))
                                  processor_instance=MuonTimingProcessor(region='CR', data_type='data'),
                                  executor=processor.futures_executor,
                                  executor_args=dict(workers=12, flatten=False),
                                  chunksize=500000,
                                 )


    ## CHANNEL - 2mu2e
    fig, ax = plt.subplots(1,1,figsize=(8,6))
    h = outputs['data']['ndsa'].integrate('channel', slice(1,2))
    hist.plot1d(h, overlay='cat', ax=ax, overflow='over', error_opts=data_err_opts)
    ax.set_title('[2mu2e|CR] mu-type leptonjet N(dsa)', x=0.0, ha="left")
    ax.set_yscale('symlog')
    ax.autoscale(axis='both', tight=True)
    ax.text(1,1,'59.74/fb (13TeV)', ha='right', va='bottom', transform=ax.transAxes)
    ax.get_yaxis().set_major_locator(SymmetricalLogLocator(base=10., linthresh=1, subs=range(1,10)))
    ax.set_xlabel(ax.get_xlabel(), x=1.0, ha="right")
    ax.set_ylabel(ax.get_ylabel(), y=1.0, ha="right")
    fig.savefig(join(outdir, 'ndsa_CR_2mu2e.png'))
    fig.savefig(join(outdir, 'ndsa_CR_2mu2e.pdf'))
    plt.close(fig)

    fig, ax = plt.subplots(1,1,figsize=(8,6))
    h = outputs['data']['mutiming'].integrate('channel', slice(1,2))
    hist.plot1d(h, overlay='cat', ax=ax, overflow='over', error_opts=data_err_opts)
    ax.set_title('[2mu2e|CR] mu-type leptonjet mean timing', x=0.0, ha="left")
    ax.autoscale(axis='both', tight=True)
    ax.text(1,1,'59.74/fb (13TeV)', ha='right', va='bottom', transform=ax.transAxes)
    ax.set_xlabel(ax.get_xlabel(), x=1.0, ha="right")
    ax.set_ylabel(ax.get_ylabel(), y=1.0, ha="right")
    fig.savefig(join(outdir, 'mutiming_CR_2mu2e.png'))
Exemplo n.º 12
0
def plot_2d(w1,
            w3,
            signal,
            path,
            invert_w1=False,
            scale=None,
            axlim=(None, None)):
    signal2 = -1 * signal.copy()

    # plot in 1000 of wn
    w1 = w1.copy() / 1e3
    w3 = w3.copy() / 1e3

    if invert_w1:
        w1 = -w1

    if scale is None:  # calculate scale, return it in meta
        scale = np.max(np.abs(signal2))

    signal2 /= scale

    # fiddle parameters to make the plots look good
    linthresh = 0.01
    linscale = 0.1
    nlevels = 100
    norm = SymLogNorm(linthresh=linthresh, linscale=linscale, vmin=-1, vmax=1)
    logloc = SymmetricalLogLocator(linthresh=linthresh, base=2)

    levels = logloc.tick_values(-1, 1)

    fig = figure()
    ax = fig.add_subplot(111, aspect='equal', adjustable='box-forced')

    qset = ax.contourf(w1, w3, signal2, nlevels, norm=norm, cmap='RdBu_r')
    c = ax.contour(w1, w3, signal2, levels=levels, colors='k', alpha=0.4)
    ax.set_xlabel(r'$\omega_\tau$ ($\times 10^3\ \mathrm{cm}^{-1}$)')
    ax.set_ylabel(r"$\omega_t$ ($\times 10^3\ \mathrm{cm}^{-1}$)")
    ax.text(0.99,
            0.01,
            r'$\mathrm{{scale:}} {!s}$'.format(latex_float(scale)),
            transform=ax.transAxes,
            horizontalalignment='right',
            verticalalignment='bottom')

    loc = matplotlib.ticker.MaxNLocator(11)
    fmt = matplotlib.ticker.ScalarFormatter(useOffset=False, useMathText=True)

    cb = fig.colorbar(qset, ax=ax, ticks=loc, format=fmt)
    cb.add_lines(c)

    ax.set_xlim(*axlim)
    ax.set_ylim(*axlim)

    #ax.grid(True)
    ax.add_artist(
        Line2D((0, 1), (0, 1),
               linewidth=2,
               color='k',
               alpha=0.5,
               transform=ax.transAxes))

    #ax.relim()
    #ax.autoscale_view()
    fig.savefig(str(path))
Exemplo n.º 13
0
    transform=ax.transAxes,
    weight=600,
    horizontalalignment="left",
    verticalalignment="top",
    size="medium",
)

# SymLog scale
# -----------------------------------------------------------------------------
ax = plt.subplot(4, 1, 3, ylim=(-2, 2))
t = 0.05
ax.set_xscale("symlog", basex=10, linthreshx=t, linscalex=1)
plt.plot(X, Y, color="C1", linewidth=1.5)
ax.set_yticks([])
ax.xaxis.set_minor_locator(
    SymmetricalLogLocator(base=10, linthresh=t, subs=np.arange(2, 10)))

ax.text(
    0.01,
    0.95,
    "Symlog scale",
    transform=ax.transAxes,
    weight=600,
    horizontalalignment="left",
    verticalalignment="top",
    size="medium",
)
ax.fill_betweenx([-2, 2], [-t, -t], [+t, +t], facecolor="black", alpha=0.1)
ax.text(
    0.50,
    0.05,
Exemplo n.º 14
0
def plot_2d(w1, w3, signal, path, invert_w1=False, scale=None, axlim=None):
    signal2 = -1 * signal
    rcParams.update(params)

    # plot in 1000 of wn
    w1 = w1.copy() / 1e3
    w3 = w3.copy() / 1e3

    if invert_w1:
        w1 = -w1

    if scale is None:  # calculate scale, return it in meta
        scale = np.max(np.abs(signal2))
        signal2 /= scale

    # fiddle parameters to make the plots look good
    linthresh = 0.01
    linscale = 0.1
    nlevels = 100
    norm = SymLogNorm(linthresh=linthresh, linscale=linscale, vmin=-1, vmax=1)
    logloc = SymmetricalLogLocator(linthresh=linthresh, base=2)

    levels = logloc.tick_values(-1, 1)

    fig = figure()
    ax = fig.add_subplot(111, aspect='equal', adjustable='box-forced')

    qset = ax.contourf(w1, w3, signal2, nlevels, norm=norm, cmap='RdBu_r')
    ax.contour(w1, w3, signal2, levels=levels, colors='k', alpha=0.4)
    cb = fig.colorbar(qset, ax=ax)

    if axlim:
        ypts = xpts = np.array(sorted(axlim)) / 1e3
        print('Using limits ', xpts, ypts)
        ax.set_xlim(xpts)
        ax.set_ylim(ypts)
    else:
        ypts = xpts = sorted([np.min(w3), np.max(w3)])
        ax.set_xlim(xpts)
        ax.set_ylim(ypts)

    ax.add_artist(
        Line2D(xpts,
               ypts,
               linewidth=2,
               color='k',
               alpha=0.5,
               transform=ax.transData))
    mainpath = Path(path)
    fullpath = mainpath.with_suffix('.full.png')
    cbpath = mainpath.with_suffix('.cb.png')
    boundsinfo = mainpath.with_suffix('.info')

    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    cb.ax.xaxis.set_visible(False)
    cb.ax.yaxis.set_visible(False)

    dpi_trans = fig.dpi_scale_trans.inverted()

    main_extent = ax.get_window_extent().transformed(dpi_trans)
    cb_extent = cb.ax.get_window_extent().transformed(dpi_trans)

    fig.savefig(str(mainpath), bbox_inches=main_extent)
    fig.savefig(str(cbpath), bbox_inches=cb_extent)
    fig.savefig(str(fullpath), bbox_inches='tight')

    with boundsinfo.open('w') as f:
        print('Main axis bounds:', file=f)
        print(repr(ax.viewLim.get_points()), file=f)
        print(file=f)

        print('Axis limits:', file=f)
        print(repr(ax.get_xlim()), file=f)
        print(repr(ax.get_ylim()), file=f)
        print(file=f)

        print('Signal scale: ', file=f)
        print(scale, file=f)
        print(file=f)

        print('Colorbar bounds:', file=f)
        print([cb.boundaries[x] for x in [0, -1]], file=f)
Exemplo n.º 15
0
def symlog_axis(vals,ax,which):
    if which=='x':
        ax.set_xscale("symlog", linthresh=1, base=10, subs=np.arange(1, 11))
        op_ax = ax.xaxis
    elif which=='y':
        ax.set_yscale("symlog", linthresh=1, base=10, subs=np.arange(1, 11))
        op_ax = ax.yaxis
    else:
        raise ValueError(f'which must be one of "x" or "y".')

    op_ax.set_minor_locator(
        SymmetricalLogLocator(base=10, linthresh=0.1, subs=np.arange(1, 10))
    )
    ax_min_sign, ax_max_sign = np.sign(vals.min()), np.sign(vals.max())
    ax_min, ax_max = np.ceil(np.log10(abs(vals.min()))), np.ceil(
        np.log10(abs(vals.max()))
    )
    op_ax.set_view_interval(ax_min_sign * 10 ** ax_min, ax_max_sign * 10 ** ax_max)

    ticklabels = []
    ticks = []
    if ax_min_sign == -1:
        if ax_max_sign == -1:
            ticklabels.extend(
                [
                    f"$\\mathdefault{{-10^{{{int(n)}}}}}$"
                    for n in np.linspace(ax_min, ax_max, int(ax_min - ax_max) + 1)
                ]
            )
            ticks.append(-np.logspace(ax_min, ax_max, int(ax_min - ax_max) + 1))
        else:
            ticklabels.extend(
                [
                    f"$\\mathdefault{{-10^{{{int(n)}}}}}$"
                    for n in np.linspace(ax_min, 0, int(ax_min) + 1)
                ]
            )
            ticks.append(-np.logspace(ax_min, 0, int(ax_min) + 1))

    if ax_max_sign == 1:
        if ax_min_sign == 1:
            ticklabels.extend(
                [
                    f"$\\mathdefault{{10^{{{int(n)}}}}}$"
                    for n in np.linspace(ax_min, ax_max, int(ax_max - ax_min) + 1)
                ]
            )
            ticks.append(np.linspace(ax_min, ax_max, int(ax_max - ax_min) + 1))
        else:
            ticklabels.append("0")
            ticklabels.extend(
                [
                    f"$\\mathdefault{{10^{{{int(n)}}}}}$"
                    for n in np.linspace(0, ax_max, int(ax_max) + 1)
                ]
            )
            ticks.append(np.array([0]))
            ticks.append(np.logspace(0, ax_max, int(ax_max) + 1))

    op_ax.set_ticks(np.concatenate(ticks))
    op_ax.set_ticklabels(ticklabels)
    return ax