Ejemplo n.º 1
0
def plot_core_occupancy(occ, path, name):
    """Plot number of compartments per core of a layer.

    :param np.ndarray occ: Core occupancy to plot. Shape is equal to the number
        of cores per axis.
    :param str path: Where to save figure.
    :param str name: Name of partition.
    """

    occ = normalizeImageDim(occ)

    fig, ax = plt.subplots()
    im = ax.imshow(occ, cmap='Blues', vmin=0, vmax=1024)
    vals = np.unique([0] + list(np.ravel(occ)))
    if 1024 - np.max(vals) > 100:
        vals = np.concatenate([vals, [1024]])
    fig.colorbar(im,
                 ticks=vals[::(len(vals) // 10) + 1],
                 fraction=0.02,
                 pad=0.04)
    ax.set_xticks(np.arange(0, occ.shape[1], occ.shape[1] // 10 + 1))
    ax.set_yticks(np.arange(0, occ.shape[0], occ.shape[0] // 10 + 1))
    ax.tick_params(which='both', left=False, bottom=False)
    ax.xaxis.set_minor_locator(IndexLocator(1, 1))
    ax.yaxis.set_minor_locator(IndexLocator(1, 1))
    ax.grid(which='minor')
    ax.set_title('Core occupancy of layer {}'.format(name))
    fig.savefig(os.path.join(path, 'coreOccupancy_{}'.format(name)),
                bbox_inches='tight')
Ejemplo n.º 2
0
def plot_multiplicity(m, path, name):
    """Plot multiplicityMap.

    :param np.array m: multiplicityMap.
    :param str path: Where to save figure.
    :param str name: Name of partition.
    """

    m = normalizeImageDim(m)

    fig, ax = plt.subplots()
    im = ax.imshow(m, cmap='Blues', vmin=0)
    vals = np.unique(m)
    fig.colorbar(im,
                 ticks=[0] + list(vals[::(len(vals) // 10) + 1]),
                 fraction=0.02,
                 pad=0.04)
    ax.set_xticks(np.arange(0, m.shape[1], m.shape[1] // 5 + 1))
    ax.set_yticks(np.arange(0, m.shape[0], m.shape[0] // 5 + 1))
    ax.set_title('Multiplicity map of input to {}'.format(name))
    ax.tick_params(which='both', left=False, bottom=False)
    ax.xaxis.set_minor_locator(IndexLocator(1, 1))
    ax.yaxis.set_minor_locator(IndexLocator(1, 1))
    ax.grid(which='minor')
    fig.savefig(os.path.join(path, 'multiplicityMap_{}'.format(name)),
                bbox_inches='tight')
Ejemplo n.º 3
0
def _patch_month(data, ax: Axes) -> Axes:
    major = IndexLocator(12, +0.4)
    minor = IndexLocator(1, +0.4)
    ax.xaxis.set_minor_locator(minor)
    ax.xaxis.set_major_locator(major)
    ax.set_xticklabels(data.index.strftime("%b %Y")[::12])
    ax.grid(True, which="major", axis="x", linestyle="--")
    return ax
Ejemplo n.º 4
0
def _patch_day(data, ax: Axes) -> Axes:
    major = IndexLocator(365, +0.4)
    minor = IndexLocator(7, +0.4)
    ax.xaxis.set_minor_locator(minor)
    ax.xaxis.set_major_locator(major)
    ax.set_xticklabels(data.index.strftime("%d %b %Y")[::365])
    ax.grid(True, which="major", axis="x")
    return ax
def plot_duration_distribution_per_day_as_line(figure: Figure,
                                               cohort: Cohort) -> Figure:
    assert cohort.is_duration_events()

    df = event_duration_agg(cohort, "count").sort_values("duration")
    ax = figure.gca()
    ax.plot(df.duration, df["count(1)"])
    ax.set_yscale("log")

    major = IndexLocator(365, +0.0)
    minor = IndexLocator(30, +0.0)
    ax.xaxis.set_minor_locator(minor)
    ax.xaxis.set_major_locator(major)
    ax.grid(True, which="major", axis="x")
    return figure
Ejemplo n.º 6
0
def get_locator():
    """
    the axes cannot share the same locator, so this is a helper
    function to generate locators that have identical functionality
    """

    return IndexLocator(10, 1)
Ejemplo n.º 7
0
    def draw(self):
        if not hasattr(self, 'ax'):
            self.ax = self.figure.add_subplot(111)
        ax = self.ax
        ax.clear()

        handles = []
        labels = []
        self.field = self.parent.object_panel.field

        for object, name, marker, color in self.parent.object_panel.get_objects(
        ):
            xs = []
            ys = []
            l = object
            for x in range(self.field.base):
                for y in range(self.field.base):
                    if object.eval(x, y) == 0:
                        xs.append(x)
                        ys.append(y)
            handles.append(
                ax.scatter(xs, ys, marker=marker, s=100, color=color))
            labels.append(name)

        ax.set_xlim(-0.5, self.field.base - 0.5)
        ax.set_ylim(-0.5, self.field.base - 0.5)

        ax.xaxis.set_major_locator(IndexLocator(-0.5, 1))
        ax.xaxis.set_minor_locator(IndexLocator(0, 1))
        ax.yaxis.set_major_locator(IndexLocator(-0.5, 1))
        ax.yaxis.set_minor_locator(IndexLocator(0, 1))

        ax.xaxis.set_major_formatter(NullFormatter())
        ax.xaxis.set_minor_formatter(ScalarFormatter())
        ax.yaxis.set_major_formatter(NullFormatter())
        ax.yaxis.set_minor_formatter(ScalarFormatter())

        ax.set_xticks(range(0, self.field.base), minor=True)
        ax.set_yticks(range(0, self.field.base), minor=True)

        ax.set_xticks([x + 0.5 for x in range(0, self.field.base)])
        ax.set_yticks([x + 0.5 for x in range(0, self.field.base)])

        ax.grid(True)
        self.repaint()
Ejemplo n.º 8
0
    def plot(self):
        fig = plt.figure()
        ax = fig.add_subplot(111)

        handles = []
        labels = []
        for object, name, marker in self.objects:
            xs = []
            ys = []
            l = object
            for x in range(59):
                for y in range(59):
                    if object.eval(x, y) == 0:
                        xs.append(x)
                        ys.append(y)
            print object, name, marker
            print zip(xs, ys)
            handles.append(ax.scatter(xs, ys, marker=marker, s=100))
            labels.append(name)

        ax.set_xlim(-0.5, 10.5)
        ax.set_ylim(-0.5, 10.5)

        ax.xaxis.set_major_locator(IndexLocator(-0.5, 1))
        ax.xaxis.set_minor_locator(IndexLocator(0, 1))
        ax.yaxis.set_major_locator(IndexLocator(-0.5, 1))
        ax.yaxis.set_minor_locator(IndexLocator(0, 1))

        ax.xaxis.set_major_formatter(NullFormatter())
        ax.xaxis.set_minor_formatter(ScalarFormatter())
        ax.yaxis.set_major_formatter(NullFormatter())
        ax.yaxis.set_minor_formatter(ScalarFormatter())

        ax.set_xticks(range(0, 59), minor=True)
        ax.set_yticks(range(0, 59), minor=True)

        ax.set_xticks([x + 0.5 for x in range(0, 59)])
        ax.set_yticks([x + 0.5 for x in range(0, 59)])

        ax.grid(True)
        plt.figlegend(handles, labels, scatterpoints=1, loc=1)

        plt.show()
Ejemplo n.º 9
0
def plot_endmembers(args, endmember_array):

    # Return number of regional clusters
    n_regional_clusters = return_nclusters(args)

    # Load and interpolate rainfall
    rainfall_ts_file = os.path.join(
        args.base_dir, 'saved_rainfall_regions',
        'cluster_center_rainfall_ts_csvs',
        '{}_rainfall_regions_nclusters_{}_normalized_monthly_ts.csv'.format(
            args.unmixing_region, n_regional_clusters))
    monthly_rainfall_ts = np.array(pd.read_csv(rainfall_ts_file, index_col=0))

    rainfall_ts = interpolate_rainfall(args, monthly_rainfall_ts)

    # Set up variables for plotting
    xrange = range(len(rainfall_ts[0]))
    ticknames = ['01/2017', '01/2018', '01/2019']
    minors = np.linspace(0, 69, 37)

    fig, ax = plt.subplots(1, n_regional_clusters)

    for ax_ix in range(n_regional_clusters):
        twin_ax = ax[ax_ix].twinx()

        # ax.plot(xrange[0:23], rainfall_ts[0:23], label = 'Monthly rainfall', linestyle = '-')
        ax[ax_ix].plot(xrange,
                       normalize(endmember_array[:, ax_ix * 3]),
                       label='In phase',
                       color='r')
        ax[ax_ix].plot(xrange,
                       normalize(endmember_array[:, ax_ix * 3 + 1]),
                       label='Out of phase',
                       color='g')
        ax[ax_ix].plot(xrange,
                       endmember_array[:, ax_ix * 3 + 2],
                       label='Dark',
                       color='b')
        ax[ax_ix].set_title(args.unmixing_region + ', region {}'.format(ax_ix))
        ax[ax_ix].set_xlabel('Month')
        ax[ax_ix].grid('on')
        ax[ax_ix].legend(loc='upper left')

        ax[ax_ix].set_xticklabels(ticknames)
        ax[ax_ix].xaxis.set_major_locator(IndexLocator(23, 0))

        ax[ax_ix].xaxis.set_minor_locator(FixedLocator(minors))
        ax[ax_ix].tick_params(axis='x', which='both', length=2)

        twin_ax.plot(xrange, rainfall_ts[ax_ix], linestyle=':', color=cmap[0])

    plt.show()
Ejemplo n.º 10
0
def plot_coreIdMap(m, path, name):
    """Plot coreIdMap.

    :param np.array m: coreIdMap.
    :param str path: Where to save figure.
    :param str name: Name of partition.
    """

    yy = normalizeImageDim(m)
    shape = yy.shape

    fig, ax = plt.subplots()
    im = ax.imshow(yy, cmap='Blues', vmin=0)
    vals = np.unique(yy)
    fig.colorbar(im,
                 ticks=vals[::len(vals) // 10 + 1],
                 fraction=0.02,
                 pad=0.04)
    ax.set_xticks(np.arange(0, shape[1], shape[1] // 5 + 1))
    ax.set_yticks(np.arange(0, shape[0], shape[0] // 5 + 1))
    ax.tick_params(which='both', left=False, bottom=False)
    ax.xaxis.set_minor_locator(IndexLocator(1, 1))
    ax.yaxis.set_minor_locator(IndexLocator(1, 1))
    ax.grid(which='minor')

    if m.ndim == 3:
        num_depth_partitions = len(np.unique(m[0, 0, :]))
        num_channels = m.shape[-1]
        s = '' if num_depth_partitions == 1 else 's'
        ss = '' if num_channels == 1 else 's'
        ax.set_title('Core ID map of layer {}\n({} partition{} along '
                     '{} channel{}.)'.format(name, num_depth_partitions, s,
                                             num_channels, ss))
    else:
        ax.set_title('Core ID map of layer {}'.format(name))

    fig.savefig(os.path.join(path, 'partition_{}'.format(name)),
                bbox_inches='tight')
Ejemplo n.º 11
0
def draw_combined(datas, names):

    stop = max(map(lambda distr: distr.index.max(), datas))
    index = pd.date_range(start=pd.to_datetime(STARTUNIXTIME, unit="s"),
                          end=stop, freq="1d")
    indexh = pd.date_range(start=pd.to_datetime(STARTUNIXTIME, unit="s"),
                          end=stop, freq="1d")

    df = pd.DataFrame(index=index)
    total = pd.Series(data=150000.0, index=indexh)
    dfh = pd.DataFrame(index=indexh)


    for distr, name in zip(datas, names):
        df[name] = distr.resample("1d").last().fillna(method='ffill')
        # total += df[name].resample("1h").last().fillna(method='ffill').fillna(0.0).cumsum()
        # dfh[name] = df[name].resample("1h").last().fillna(method='ffill').fillna(0.0).cumsum()
        total += df[name].resample("1h").last().fillna(method='ffill').fillna(0.0).cumsum()
        dfh[name] = df[name].resample("1h").last().fillna(method='ffill').fillna(0.0).cumsum()


    x_compat = True
    # print(df)

    panes = 2
    fig, axs = plt.subplots(panes, 1, tight_layout=True, sharex=True, squeeze=True, figsize=(30, 20))

    applyTicks(axs, 900, stop.timestamp())



    df.plot(ax=axs[0], lw=9, x_compat=x_compat)

    dfh.plot(ax=axs[1], lw=9, x_compat=x_compat)
    total.plot(ax=axs[1], lw=9, x_compat=x_compat)

    axs[1].axhline(y=1000000, lw=1.0, color="black")
    axs[1].axhline(y=450000, lw=1.0, color="black")
    axs[1].axhline(y=400000, lw=1.0, color="black")

    loc = IndexLocator(100000, 100000)
    axs[1].yaxis.set_major_locator(loc)
    formater = ScalarFormatter(useOffset=False)
    formater.set_powerlimits((-10,10))
    axs[1].yaxis.set_major_formatter(formater)

    plt.savefig("combo.png", dpi=300)
    plt.close()
Ejemplo n.º 12
0
def draw_line_chart(x, y, title, gap, fname):
    plt.title(title)
    # 返回当前的Axes对象
    ax = plt.gca()
    # 设置边框线和水平横线
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.grid(axis='y')
    # 设置x/y轴刻度
    x_locator = IndexLocator(gap, 0)
    ax.xaxis.set_major_locator(x_locator)
    ax.set_xlim(0, x[-1])
    ax.set_ylim(0, 80)
    plt.plot(x, y)
    pl.xticks(rotation=90)
    # 保存
    plt.savefig(fname)
    plt.close('all')
Ejemplo n.º 13
0
def plot_survival():
    width = 0.5
    fig, ax = plt.subplots()
    t_bar = ax.bar(0, np.mean(survivals['Tiger']), width,
            yerr=sem(survivals['Tiger']), color='orange')
    g_bar = ax.bar(1, np.mean(survivals['Giraffe']), width,
            yerr=sem(survivals['Giraffe']), color='yellow')
    e_bar = ax.bar(2, np.mean(survivals['Elephant']), width,
            yerr=sem(survivals['Elephant']), color='purple')

    #ax.legend((t_bar, g_bar, e_bar), ('Tiger', 'Giraffe', 'Elephant'), loc=2)

    ax.set_xticklabels(['Tiger', 'Giraffe', 'Elephant'])

    tick_locator = IndexLocator(1, 0.25)
    ax.xaxis.set_major_locator(tick_locator)

    plt.title('Average number of steps survived by species (N=%d)' % (N*3))
    plt.ylabel('Avg. steps alive (with standard error)')
    plt.show()
Ejemplo n.º 14
0
def generate_tau_map(cells, cam, show=False):
    '''
    Ray-traces optical depth and plots as a 2D map
    '''
    import numpy as np
    from pymses.analysis.splatting.map_bin2d import histo2D

    # odt = OpticalDepthTracer(snap)
    # cam = snap.camera()
    # cells = odt.process(camera)

    tau = cells["tau"]
    pts = np.zeros_like(cells.points)
    pts[:, :2], pts[:, 2] = cam.project_points(cells.points)
    centered_map_box = cam.get_map_box()
    map_range = np.array(
        [[centered_map_box.min_coords[0], centered_map_box.max_coords[0]],
         [centered_map_box.min_coords[1], centered_map_box.max_coords[1]],
         [centered_map_box.min_coords[2], centered_map_box.max_coords[2]]])

    map = histo2D(pts, [256, 256], map_range, {"tau": tau})

    map_unit = snap.info['unit_density'] * snap.info['unit_length']
    map = np.log10(map["tau"] * map_unit.express(snap.C.Msun / snap.C.kpc**2))

    if show:
        from matplotlib import pyplot as plt
        from matplotlib.ticker import FormatStrFormatter, IndexLocator
        vmin = np.min(map[map > 0.])
        plt.imshow(map, origin='lower')
        fo = FormatStrFormatter("$10^{%d}$")
        offset = np.ceil(vmin) - vmin
        lo = IndexLocator(1.0, offset)
        cb = plt.colorbar(ticks=lo, format=fo)
        # Set colorbar lable
        cb.set_label("$M_{\odot}/kpc^{2}$")
        plt.show(block=False)

    return map
Ejemplo n.º 15
0
def plot_times():
    file_mapping = defaultdict(list)
    for file in sorted(os.listdir()):
        if not file.endswith(('start', 'end')):
            continue
        day = int(file.split('.')[0][3:])
        file_mapping[day].append(file)

    days = []
    deltas = []
    for day, files in file_mapping.items():
        for file in files:
            with open(file) as f:
                if file.endswith('start'):
                    # multiple lines: pairs of break/end dates
                    startlines = f.readlines()
                else:
                    endline = f.readline()
        timelines = startlines + [endline]

        times = [datetime.strptime(timeline.strip(), '%a %d %b %X %Z %Y') for timeline in timelines]
        intervals = zip(times[::2], times[1::2])  # normally a single [from, to] interval
        delta = 0
        for fr, to in intervals:
            delta += (to - fr).seconds/60
        days.append(day)
        deltas.append(delta)

    fig, ax = plt.subplots()
    ax.plot(days, deltas, 's-')
    ax.grid(True)
    ax.set_xlabel('day')
    ax.set_ylabel('minutes')
    ax.xaxis.set_major_locator(IndexLocator(base=1, offset=0))
    ax.set_xlim(0.5, 25.5)
    fig.tight_layout()

    return fig
Ejemplo n.º 16
0
def plot_cm(y_test, y_pred_class, classes=['NON-default', 'DEFAULT']):
    # plots confusion matrix
    fig, ax = plt.subplots()
    cm = confusion_matrix(y_test, y_pred_class)

    im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
    ax.figure.colorbar(im, ax=ax)
    plt.title("Confusion Matrix")
    ax.set(yticks=[-0.5, 1.5],
           xticks=[0, 1],
           yticklabels=classes,
           xticklabels=classes)
    ax.yaxis.set_major_locator(IndexLocator(base=1, offset=0.5))
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j,
                 i,
                 format(cm[i, j], 'd'),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
Ejemplo n.º 17
0
def plot_waterfall(arr, samp_rate, center_freq, rps, fft, filename):
    gc.collect()

    fig = Figure(figsize=(12.8, 20.8), dpi=200)
    FigureCanvas(fig)

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

    im = ax.imshow(arr,
                   cmap=cm.nipy_spectral,
                   interpolation='none',
                   vmin=int(np.mean(arr)),
                   vmax=arr.max(),
                   alpha=1,
                   aspect='auto',
                   origin='lower')
    cb = fig.colorbar(im, ax=ax, aspect=50)
    cb.set_label('Power (dBFS)')

    cell_freq = samp_rate / 10.0
    center_tick = fft / 2
    carriers_per_tick = int(cell_freq * fft / samp_rate)
    nticks = 9

    x_ticks = [center_tick]
    x_tick_labels = [float_to_str(center_freq)]
    for i in range(nticks / 2):
        x_ticks.append((i + 1) * carriers_per_tick + center_tick)
        x_ticks.insert(0, center_tick - (i + 1) * carriers_per_tick)
        x_tick_labels.append(float_to_str(center_freq + (i + 1) * cell_freq))
        x_tick_labels.insert(0,
                             float_to_str(center_freq - (i + 1) * cell_freq))

    n_rows_per_tick = 60 * rps
    y_ticks = []
    y_tick_labels = []
    j = 0
    for i in range(0, len(arr), n_rows_per_tick):
        y_ticks.append(i)
        y_tick_labels.append(j * 60)
        j = j + 1

    ax.set_xticks(x_ticks)
    ax.set_xticklabels(x_tick_labels, size='x-large')
    if len(y_ticks) > 0:
        ax.set_yticks(y_ticks)
        ax.set_yticklabels(y_tick_labels, size='x-large')
    ax.grid(b='on',
            linestyle='dashed',
            linewidth=1,
            color='#000000',
            alpha=0.3)
    ax.get_yaxis().set_minor_locator(IndexLocator(10 * rps, 0))
    ax.get_yaxis().set_major_locator(IndexLocator(60 * rps, 0))
    ax.get_yaxis().grid(which='minor',
                        color='black',
                        linestyle='-',
                        linewidth=0.05,
                        alpha=0.7)
    ax.get_xaxis().grid(which='minor',
                        color='black',
                        linestyle='-',
                        linewidth=0.1,
                        alpha=0.6)
    ax.get_xaxis().set_minor_locator(AutoMinorLocator(10))
    ax.set_xlabel('Frequency (Hz)')
    ax.set_ylabel('Time (seconds)')

    if filename != '':
        fig.savefig(filename,
                    bbox_inches='tight',
                    pad_inches=0.2,
                    format='png')

    with io.BytesIO() as buf:
        buf = io.BytesIO()
        fig.savefig(buf, bbox_inches='tight', pad_inches=0.2, format='png')
        return buf.getvalue()
Ejemplo n.º 18
0
    def plot(self, figure=None, overlays=[], colorbar=True, vmin=None,
             vmax=None, linear=True, showz=True, yres=DEFAULT_YRES,
             max_dist=None, **matplotlib_args):
        """
        Plot spectrogram onto figure.

        Parameters
        ----------
        figure : `~matplotlib.Figure`
            Figure to plot the spectrogram on. If None, new Figure is created.
        overlays : list
            List of overlays (functions that receive figure and axes and return
            new ones) to be applied after drawing.
        colorbar : bool
            Flag that determines whether or not to draw a colorbar. If existing
            figure is passed, it is attempted to overdraw old colorbar.
        vmin : float
            Clip intensities lower than vmin before drawing.
        vmax : float
            Clip intensities higher than vmax before drawing.
        linear : bool
            If set to True, "stretch" image to make frequency axis linear.
        showz : bool
            If set to True, the value of the pixel that is hovered with the
            mouse is shown in the bottom right corner.
        yres : int or None
            To be used in combination with linear=True. If None, sample the
            image with half the minimum frequency delta. Else, sample the
            image to be at most yres pixels in vertical dimension. Defaults
            to 1080 because that's a common screen size.
        max_dist : float or None
            If not None, mask elements that are further than max_dist away
            from actual data points (ie, frequencies that actually have data
            from the receiver and are not just nearest-neighbour interpolated).
        """
        # [] as default argument is okay here because it is only read.
        # pylint: disable=W0102,R0914
        if linear:
            delt = yres
            if delt is not None:
                delt = max(
                    (self.freq_axis[0] - self.freq_axis[-1]) / (yres - 1),
                    _min_delt(self.freq_axis) / 2.
                )
                delt = float(delt)

            data = _LinearView(self.clip_values(vmin, vmax), delt)
            freqs = np.arange(
                self.freq_axis[0], self.freq_axis[-1], -data.delt
            )
        else:
            data = np.array(self.clip_values(vmin, vmax))
            freqs = self.freq_axis

        figure = plt.gcf()

        if figure.axes:
            axes = figure.axes[0]
        else:
            axes = figure.add_subplot(111)

        params = {
            'origin': 'lower',
            'aspect': 'auto',
        }
        params.update(matplotlib_args)
        if linear and max_dist is not None:
            toplot = ma.masked_array(data, mask=data.make_mask(max_dist))
        else:
            toplot = data
        im = axes.imshow(toplot, **params)

        xa = axes.get_xaxis()
        ya = axes.get_yaxis()

        xa.set_major_formatter(
            FuncFormatter(self.time_formatter)
        )

        if linear:
            # Start with a number that is divisible by 5.
            init = (self.freq_axis[0] % 5) / data.delt
            nticks = 15.
            # Calculate MHz difference between major ticks.
            dist = (self.freq_axis[0] - self.freq_axis[-1]) / nticks
            # Round to next multiple of 10, at least ten.
            dist = max(round(dist, -1), 10)
            # One pixel in image space is data.delt MHz, thus we can convert
            # our distance between the major ticks into image space by dividing
            # it by data.delt.

            ya.set_major_locator(
                IndexLocator(
                    dist / data.delt, init
                )
            )
            ya.set_minor_locator(
                IndexLocator(
                    dist / data.delt / 10, init
                )
            )

            def freq_fmt(x, pos):
                # This is necessary because matplotlib somehow tries to get
                # the mid-point of the row, which we do not need here.
                x = x + 0.5
                return self.format_freq(self.freq_axis[0] - x * data.delt)
        else:
            freq_fmt = _list_formatter(freqs, self.format_freq)
            ya.set_major_locator(MaxNLocator(integer=True, steps=[1, 5, 10]))

        ya.set_major_formatter(
            FuncFormatter(freq_fmt)
        )

        axes.set_xlabel(self.t_label)
        axes.set_ylabel(self.f_label)
        # figure.suptitle(self.content)

        figure.suptitle(
            ' '.join([
                get_day(self.start).strftime("%d %b %Y"),
                'Radio flux density',
                '(' + ', '.join(self.instruments) + ')',
            ])
        )

        for tl in xa.get_ticklabels():
            tl.set_fontsize(10)
            tl.set_rotation(30)
        figure.add_axes(axes)
        figure.subplots_adjust(bottom=0.2)
        figure.subplots_adjust(left=0.2)

        if showz:
            axes.format_coord = self._mk_format_coord(
                data, figure.gca().format_coord)

        if colorbar:
            if len(figure.axes) > 1:
                Colorbar(figure.axes[1], im).set_label("Intensity")
            else:
                figure.colorbar(im).set_label("Intensity")

        for overlay in overlays:
            figure, axes = overlay(figure, axes)

        for ax in figure.axes:
            ax.autoscale()
        if isinstance(figure, SpectroFigure):
            figure._init(self, freqs)
        return axes
Ejemplo n.º 19
0
def plot_sh_real_coeffs(l_list, m_list, coeffs, c_lims = None, ax = None, show = True, add_cbar = True, label = None, l_lims_plot = None, flip = False, stack_vertical = False, in_ticks = False, abs_plot = True, x_label = 'Angular order, $\ell$', y_label = 'Azimuthal order, $m$'):
    '''
    Plot spherical harmonics on a grid.
    '''
    
    # Put the list of coefficients onto a grid, for plotting.
    # k Index in list.
    # i x-index in grid.
    # j y-index in grid.
    # l l-value in list.
    # m m-value in list.
    l_max = np.max(l_list)
    m_max = np.max(m_list)
    #
    coeff_grid          = np.zeros((l_max + 1, 2*m_max + 1))
    coeff_grid[:, :]    = np.nan
    # 
    k = 0
    for l in range(l_max + 1):
        
        i = l
        
        for m in range(-l, (l + 1)):
            
            # Using - m instead of + m agrees with SHTools, but I don't see
            # why.
            j = l_max + m
            coeff_grid[i, j] = coeffs[k]

            k = k + 1
    
    # Calculate absolute values.
    abs_coeff_grid = np.abs(coeff_grid)
    
    # Define the corners of the cells for a pcolor plot.
    l_corners = np.array(range(l_max + 2)) - 0.5
    m_corners = np.array(range(-(m_max), (m_max + 2))) - 0.5

    # Create axes if necessary.
    if ax is None:
        
        fig = plt.figure()
        ax  = plt.gca()
    
    # Create the color map.
    if abs_plot: 
        
        c_map     = plt.get_cmap('plasma')

    else:

        c_map   = plt.get_cmap('seismic')

    c_map.set_bad('grey')

    #
    if c_lims is None:
        
        if abs_plot:
            
            c_lims = [0.0, np.nanmax(abs_coeff_grid)]

        else:

            c_max = np.nanmax(abs_coeff_grid)
            c_lims = [-c_max, c_max]
    # 
    c_norm          = mpl.colors.Normalize(
                         vmin = c_lims[0],
                         vmax = c_lims[1])
    
    if abs_plot:

        array = abs_coeff_grid

    else:

        array = coeff_grid

    # Plot the coefficients.
    # The choice of axes can be flipped.
    if flip:

        image = ax.pcolormesh(m_corners, l_corners, array, 
                                norm = c_norm,
                                cmap = c_map)

    else:

        image = ax.pcolormesh(l_corners, m_corners, array.T,
                                norm = c_norm,
                                cmap = c_map)
    
    # Aspect 1.0 is preferable, but can be hard for arranging subplots.
    #ax.set_aspect(1.0)

    # Apply the axis limits.
    if l_lims_plot is None:

        l_lims_plot = [0.0, l_max]
        
    if flip:

        ax.set_ylim([-0.5, l_max + 0.5])
        ax.set_xlim([-(m_max + 0.5), m_max + 0.5])

    else:

        ax.set_xlim([-0.5, l_max + 0.5])
        ax.set_ylim([-(m_max + 0.5), m_max + 0.5])

    # Create the axis labels.
    font_size_label = 12
    if flip:

        x_label_temp = x_label
        x_label = y_label
        y_label = x_label_temp

    if y_label is not None:

        ax.set_ylabel(y_label, fontsize = font_size_label)

    if x_label is not None:

        ax.set_xlabel(x_label, fontsize = font_size_label)

    # Add the color bar.
    if add_cbar:
        
        c_bar = plt.colorbar(
                image,
                cax         = ax.cax,
                orientation = 'horizontal',)

        if abs_plot:

            c_bar_label = 'Magnitude of coefficients'

        else:
            
            c_bar_label = 'Coefficients'

        c_bar.set_label(c_bar_label, fontsize = font_size_label)
    
    # Force integer ticks.
    ax.xaxis.set_major_locator(MaxNLocator(integer = True))
    ax.yaxis.set_major_locator(MaxNLocator(integer = True))

    # Create a label on the plot, e.g. |Ulm|.
    if label is not None:
        
        label = '|{}$_{{lm}}|$'.format(label)
        ax.text(0.1, 0.9, label, transform = ax.transAxes)
    
    # Change the ticks and their labels to be on the inside of the
    # x-axis (if requested).
    if in_ticks:

        ax.tick_params(axis = "x", direction = "in", pad = -15)

    # Tidy up the ticks.
    ax.xaxis.set_major_locator(MultipleLocator(5.0))
    ax.xaxis.set_minor_locator(IndexLocator(base = 1.0, offset = 0.5))
    ax.yaxis.set_major_locator(MultipleLocator(5.0))
    ax.yaxis.set_minor_locator(IndexLocator(base = 1.0, offset = 0.5))
    ax.grid(which = 'major', axis = 'both', alpha = 0.3, linewidth = 1)
    ax.grid(which = 'minor', axis = 'both', alpha = 0.1, linewidth = 1)

    if show:
        
        plt.show()
        
    return image
Ejemplo n.º 20
0
def plot_grid_scores(grid_scores,
                     best_point,
                     params,
                     name,
                     label_all_ticks=False,
                     n_ticks=10,
                     title=None,
                     format='png',
                     path=PLOTS_DIR):

    param_names = sorted(grid_scores[0][0].keys())
    param_values = dict([(pname, []) for pname in param_names])
    for pvalues, score, cv_scores in grid_scores:
        for pname in param_names:
            param_values[pname].append(pvalues[pname])

    # remove duplicates
    for pname in param_names:
        param_values[pname] = np.unique(param_values[pname]).tolist()

    scores = np.empty(
        shape=[len(param_values[pname]) for pname in param_names])

    for pvalues, score, cv_scores in grid_scores:
        index = []
        for pname in param_names:
            index.append(param_values[pname].index(pvalues[pname]))
        scores.itemset(tuple(index), score)

    fig = plt.figure(figsize=(6, 6), dpi=100)
    ax = plt.axes([.15, .15, .95, .75])
    ax.autoscale(enable=False)
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')
    #cmap = cm.get_cmap('Blues_r', 100)
    #cmap = cm.get_cmap('gist_heat', 100)
    #cmap = cm.get_cmap('gist_earth', 100)
    cmap = cm.get_cmap('jet', 100)

    x = np.array(param_values[param_names[1]])
    y = np.array(param_values[param_names[0]])
    extent = (min(x), max(x), min(y), max(y))
    smoothed_scores = ndimage.gaussian_filter(scores, sigma=3)
    min_score, max_score = smoothed_scores.min(), smoothed_scores.max()
    score_range = max_score - min_score
    levels = np.linspace(min_score, max_score, 30)
    img = ax.contourf(smoothed_scores,
                      levels=levels,
                      cmap=cmap,
                      vmin=min_score - score_range / 4.,
                      vmax=max_score)
    cb = plt.colorbar(img, fraction=.06, pad=0.03, format='%.3f')
    cb.set_label('AUC')

    # label best point
    y = param_values[param_names[0]].index(best_point[param_names[0]])
    x = param_values[param_names[1]].index(best_point[param_names[1]])
    ax.plot([x], [y],
            marker='o',
            markersize=10,
            markeredgewidth=2,
            markerfacecolor='none',
            markeredgecolor='k')
    ax.set_ylim(extent[2], extent[3])
    ax.set_xlim(extent[0], extent[1])

    if label_all_ticks:
        plt.xticks(range(len(param_values[param_names[1]])),
                   param_values[param_names[1]])
        plt.yticks(range(len(param_values[param_names[0]])),
                   param_values[param_names[0]])
    else:
        trees = param_values[param_names[1]]

        def tree_formatter(x, pos):
            if x < 0 or x >= len(trees):
                return ''
            return str(trees[int(x)])

        leaves = param_values[param_names[0]]

        def leaf_formatter(x, pos):
            if x < 0 or x >= len(leaves):
                return ''
            return '%.3f' % leaves[int(x)]

        ax.xaxis.set_major_formatter(FuncFormatter(tree_formatter))
        ax.yaxis.set_major_formatter(FuncFormatter(leaf_formatter))

        #ax.xaxis.set_major_locator(MaxNLocator(n_ticks, integer=True,
        #    prune='lower', steps=[1, 2, 5, 10]))
        ax.xaxis.set_major_locator(IndexLocator(20, -1))
        xticks = ax.xaxis.get_major_ticks()
        xticks[-1].label1.set_visible(False)
        #ax.yaxis.set_major_locator(MaxNLocator(n_ticks, integer=True,
        #    steps=[1, 2, 5, 10], prune='lower'))
        ax.yaxis.set_major_locator(IndexLocator(20, -1))
        yticks = ax.yaxis.get_major_ticks()
        yticks[-1].label1.set_visible(False)
        #xlabels = ax.get_xticklabels()
        #for label in xlabels:
        #    label.set_rotation(45)

    ax.set_xlabel(params[param_names[1]], position=(1., 0.), ha='right')
    ax.set_ylabel(params[param_names[0]], position=(0., 1.), ha='right')

    #ax.set_frame_on(False)
    #ax.xaxis.set_ticks_position('none')
    #ax.yaxis.set_ticks_position('none')
    ax.text(
        0.1,
        0.9,
        "{0} Category\nBest AUC = {1:.3f}\nTrees = {2:d}\nFraction = {3:.3f}".
        format(name, scores.max(), best_point[param_names[1]],
               best_point[param_names[0]]),
        ha='left',
        va='top',
        transform=ax.transAxes,
        bbox=dict(pad=10, facecolor='none', edgecolor='none'))

    if title:
        plt.suptitle(title)

    plt.axis("tight")
    plt.savefig(os.path.join(
        path, "grid_scores_{0}.{1}".format(name.lower(), format)),
                bbox_inches='tight')
    plt.clf()
Ejemplo n.º 21
0
         marker='v',
         markerfacecolor='None',
         color=clr[1])
ax1.plot(np.arange(1, 7),
         num_sig_d1000[1],
         '--',
         alpha=0.7,
         label=r'$d=1000$, spurious',
         marker='s',
         markerfacecolor='None',
         color=clr[5])
ax1.axhline(y=4, color=clr[3], linestyle='--', alpha=0.4, linewidth=0.7)
ax1.set_ylim(-0.5, 4.5)
ax1.set_xlabel(r'$\tau$')
ax1.set_ylabel('Number of sig. variables')
ax1.xaxis.set_major_locator(IndexLocator(base=1, offset=0))
ax1.legend()
ax1.grid(True)

fig.savefig('num_split.pdf')

plt.style.use('ggplot')

fig, ax2 = plt.subplots(1, 1, figsize=(5, 3), constrained_layout=True)

clr = plt.rcParams['axes.prop_cycle'].by_key()['color']

for ct, me, y in zip(beta_t_d1000[:4, 1],
                     [cd_d1000[1]] * len(beta_t_d1000[:4, 1]),
                     range(len(beta_t_d1000[:4, 1]))[::-1]):
    ax2.plot((ct - me, ct + me), (y, y),
Ejemplo n.º 22
0
  def visualize(self, metric_id=0, debug=False):
    """ Generate visualization in which:
          Rows = schools
          Boxes = regions (neighborhoods)
          Sub-boxes = students
            -> which are colored according to the specified metric (student performance, income, etc.)


          school configs has list of schools
          ea school has list of tuples of stats for each region

          district_state: [schools: [regions: [residents: []]]]
    """

    # test_district_state = [
    #   [[1],[1],[1],[2],[3], [1],[1],[1],[1],[1], [1],[1],[1]],
    #   [[3],[3],[3],[4],[4]]
    # ]
    # district_state = np.array(test_district_state)

    # school_configs = [[(5,0), (5,0), (3,0)], [(5,0)]]
    # self.initial_params = {'n_iters':2, 'school_configs':school_configs,
    #                        'district_configs':[]}

    # Collect school metrics
    metrics = []
    max_students_per_region = 0
    school_i = 0
    for school in self.initial_params['school_configs']:
      #(n_residents, income_avg, income_sd, school_perf_avg, school_perf_sd)
      school_metrics = []
      student_i = 0
      for region in school:
        # n_residents = len(region)
        n_residents = region[0]
        if debug:
          print "n_residents", n_residents
        if n_residents > max_students_per_region:
          max_students_per_region = n_residents # update max students
        region_metrics = sorted([student[metric_id]
            for student in self.district_state[school_i][student_i:student_i+n_residents]], reverse=True)
        school_metrics.append(region_metrics)
        if debug:
          print "region_metrics", region_metrics
        student_i += n_residents
      metrics.append(school_metrics)
      if debug:
        print "school_metrics", school_metrics
      school_i += 1
    max_regions_per_school = np.max([len(school_metrics) for school_metrics in metrics])

    # Convert metrics to grid layout
    n_super_rows = len(metrics) # num schools
    n_super_cols =  max_regions_per_school # max num regions assigned to a school
    box_dim = int(math.ceil(max_students_per_region**(0.5))) # square dimensions to contain max num students in a region
    if debug:
      print "n_super_rows: %d, n_super_cols: %d, box_dim: %d" % (n_super_rows, n_super_cols, box_dim)

    # grid = np.zeros((n_super_rows * box_dim, n_super_cols * box_dim))
    grid = np.empty((n_super_rows * box_dim, n_super_cols * box_dim))
    grid[:] = np.nan
    for school_id in range(n_super_rows):
      school_metrics = metrics[school_id]
      for region_id in range(len(school_metrics)):
        cur_box = np.array(school_metrics[region_id])
        cur_box.resize(box_dim, box_dim)
        if debug:
          print "school_id: %d, region_id: %d" % (school_id, region_id)
        start_row = school_id * box_dim
        start_col = region_id * box_dim
        grid[start_row:(start_row+box_dim), start_col:(start_col+box_dim)] = cur_box
    # grid[grid == 0.0] = np.nan # Set empty entries to NaN (to leave un-colored)
    if debug:
      print "grid:", grid

    # Create plot
    fig = plt.figure()
    ax = fig.add_subplot(111)
    im = plt.imshow(grid, cmap=plt.cm.coolwarm, interpolation='nearest', origin='upper', vmin=-6, vmax=6)
    minor_locator = IndexLocator(box_dim, 0)
    ax.yaxis.set_minor_locator(minor_locator)
    ax.xaxis.set_minor_locator(minor_locator)
    plt.colorbar()
    ax.grid(which = 'minor', axis='y', color='w', linewidth=5)
    ax.grid(which = 'minor', axis='x', color='w', linewidth=2)
    plt.show()
Ejemplo n.º 23
0
    def report_reactionmeddrapt_by_occurcountry(self,
                                                cached_data=False,
                                                debug=False):
        if cached_data:
            if debug:
                print("fetching cached data for report...")
            df = pandas.read_pickle(
                "../data/cached_reactionmeddrapt_by_occurcountry.pkl")
        else:
            if debug:
                print("fetching data for report from API...")
            df = self.get_reactionmeddrapt_by_occurcountry()
            df.to_pickle("../data/cached_reactionmeddrapt_by_occurcountry.pkl")

        if debug:
            print(df.shape)
            print("reporting")

        plt.figure()
        df.sum(axis=1).plot(kind="bar", figsize=(30, 6), fontsize=11)
        plt.title("Number of adverse events reported by country")
        plt.gcf().savefig("../output/reactions_by_country.png", dpi=100)

        plt.figure()
        df.transpose().describe().loc["count"].sort_values().plot(kind="bar",
                                                                  figsize=(32,
                                                                           12),
                                                                  fontsize=11)
        plt.title("Number of distinct adverse events reported by country")
        plt.gcf().savefig("../output/distinct_reactions_by_country.png",
                          dpi=100)

        plt.figure()
        df.transpose().describe().loc["count"].plot(kind="hist",
                                                    figsize=(15, 3),
                                                    fontsize=11)
        plt.title(
            "Histogram of number of distinct adverse events reported by country"
        )
        plt.gcf().savefig("../output/hist_distinct_reactions_by_country.png",
                          dpi=100)

        normalised_df = df.divide(df.sum(axis=1), axis=0)
        plt.figure()
        normalised_df.plot(kind="bar",
                           figsize=(32, 12),
                           fontsize=11,
                           stacked=True)
        plt.title("Normalised adverse events reported by country")
        plt.gcf().savefig("../output/normalised_reactions_by_country.png",
                          dpi=100)

        dists = pdist(normalised_df, euclidean)
        similarity_df = pandas.DataFrame(squareform(dists),
                                         columns=df.index,
                                         index=df.index)
        plt.figure()
        fig, ax = plt.subplots()
        fig.set_size_inches(40, 40)
        ax.xaxis.tick_top()
        plt.xticks(rotation=70)

        def format_fn(tick_val, tick_pos):
            if tick_val >= 0 and int(tick_val) in range(
                    len(similarity_df.index)):
                return similarity_df.index[int(tick_val)]
            else:
                return ''

        ax.xaxis.set_ticks(numpy.arange(0, len(similarity_df.index), 1))
        ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
        ax.xaxis.set_major_locator(IndexLocator(1, 0))
        ax.yaxis.set_major_formatter(FuncFormatter(format_fn))
        ax.yaxis.set_major_locator(IndexLocator(1, 0))
        plt.imshow(similarity_df, cmap='hot', interpolation='nearest')
        plt.colorbar()
        plt.gcf().savefig("../output/similar_countries_heatmap.png", dpi=200)
Ejemplo n.º 24
0
    def draw(self,
             ax=None,
             aw_per_tick=None,
             tick_offset=0,
             tick_start=0,
             tick_factor=1,
             subparts_highlighted=None,
             indicator_size=None,
             add_line=None,
             label=None,
             label_size=None):
        '''
        After being called on a properly initialised instance of a Wavescape object,
        this method draws the visual plot known as "wavescape" and generate a 
        matplotlib.pyplot figure of it. This means any of the method from this
        library can be used after this method has been called in order to
        save or alter the figure produced. 

        Parameters
        ----------
        
        ax: matplotlib figure, optional
            if provided, will draw the wavescape on it. Useful if many wavescapes need to
            be drawn in the same figure, or if the plot needs to be combined to others.
            Default value is None.
        
        aw_per_tick: numeric value, optional
            Ratio of tick per elements of the lowest level in the wavescape. If aw_per_tick has value 1,
            one horizontal axis tick will be drawn per element at the lowest hierarchical level of the wavescape, 
            if it has value 2, then a tick will be drawn each two elements and so forth. For the ticks to represent the bar numbers,
            a pre-existing knowledge of the time signature of the musical piece is required. (for instance, if a piece is in 4/4,
            and the analysis window has a size of one quarter note, then aw_per_tick needs to have value 4 for the
            ticks to correspond to bar numbers)
            Default value is None (meaning no ticks are drawn)
            
        tick_offset: int, optional
            offset value for the tick drawn according to the 'aw_per_tick' parameter. This is done
            so that musical pieces with 0th measure can have tick accurately representing the source
            material's bar numbers. Like the tick ratio, this number is relative to the analysis window's
            size and requires a pre-existing knowledge of the score.
            Its value must be higher or equal to 0 but strictly lower than aw_per_tick.
            If it has value "0", the first tick of the plot will be set to the value of 1. 
            For having the first tick of the plot set to the value of 0, leave that parameter to
            None and have a coherent value for aw_per_tick
            Default value is 0 (meaning no tick offset). 
        
        tick_start: int, optional
            Indicates at which number to start the tick numbering. We recommand, for
            classical score, to put the value "1", as most scores starts numbering their bars
            with 1 instead of 0.
            Default value is 0.
        
        tick_factor: float, optional
            Multiply the major ticks numbers displayed on the x-axis by a constant.
            Can be useful for very large pieces, where displaying a single tick on each
            bottom row element would make the x-axis hard to read. By increasing the aw_per_tick,
            and giving this parameter a certain value, it is possible to display less ticks while 
            still keeping the right indicative numbers with respect to the unit system chosen. 
            Default value is 1.0, (meaning the value displayed is consistent with the number of ticks, with 
            respect to tick_offset of course.)
        
        subparts_highlighted: tuple of numeric values, OR array of tuples of numeric values, optional
            List of subsections that needs to be highlighted with black outlines on the wavescape. Units
            are expressed in number of analysis windows. For example, if a musical piece has a 4/4 
            time signature, an analysis window of 1 quarter note and a total of 10 bars, the
            value [[20,28],[32,36]] for 'subparts_highlighted' will draw black outlines on the region
            of the wavescape corresponding to bars 5 until 7 and 8 until 9. 
            This parameter is interpreted differently if it has the shape of a single tuple. In such case,
            a subpplot corresponding to the delimitation in the tuple will be drawn instead. For instance,
            'subparts_highlighted=[20,28]' will only draw the wavescape corresponding to piece from bar
            5 to 7 (if the musical piece is in 4/4). Be careful not to write 'subparts_highlighted=[[20,28]]' 
            which is interpreted as drawing a highlight of bar 5 to 7 on the full wavescape.
            Default value is None (meaning no highlighting and no subsection of wavescape drawn)

        indicator_size: float, optional 
            Determine the factor by which to increment the size of the rounded indicators on the lateral edges of the plot that need. 
            A rounded indicator is drawn at each eight of the height of the plot if a value is provided for this argument.
            Enter the value "1.0" for the default size.
            Default value is None (meaning no vertical indicators)
        
        add_line: numeric value, optional
            if provided, this parameter represents the thickness of the black line outlining
            all element of the plot (drawing primitives).
            Default value is None.
        
        label: str, optional
            If provided, add this string as a textual label on the top left corner of the resulting plot.
            Can be used to specify the Fourier coefficient visualised on the wavescape for example.
            Default value is None
            
        label_size: float, optional
            Determine the size of the top-left label and the tick number labels if provided
            Default value is None (in which case the default 
            size of the labels is the width of the plot divided by 30)

        Returns
        -------
        Nothing, but a matplotlib.pyplot figure is produced by this method, and any method of pyplot
        can be used to alter the resulting figure (notably matplotlib.pyplot.savefig can be used to save the
        resulting figure in a file)
        '''

        start_primitive_idx = 0
        utm_w = self.matrix_primitive.shape[0]
        utm_h = self.matrix_primitive.shape[1]

        if self.matrix_primitive is None or utm_w < 1 or utm_h < 1:
            raise Exception("Cannot draw when there is nothing to draw.")

        if aw_per_tick is not None:

            if aw_per_tick < 1 or type(aw_per_tick) is not int:
                raise Exception(
                    "'aw_per_tick' must be an integer greater or equal to 1")

            if tick_factor <= 0 or (type(tick_factor) is not int
                                    and type(tick_factor) is not float):
                raise Exception(
                    "'tick_factor' must be a numeric value greater than 0")

            if tick_start < 0 or type(tick_start) is not int:
                raise Exception(
                    "'tick_start' must be a numeric value greater than or equal to 0"
                )

            #argument start_offseet is only meaningless if there is tick ratio involved in the plotting
            if type(
                    tick_offset
            ) is not int or tick_offset < 0 or tick_offset > aw_per_tick:
                raise Exception(
                    "Stat offset needs to be a positive integer that is smaller or equal to the tick ratio"
                )

        idx = 0
        primitive_half_width = 0
        while primitive_half_width == 0 and idx < utm_w:
            elem = self.matrix_primitive[0][idx]
            if elem:
                #needed for highlights and some tick ofsetting later.
                primitive_half_width = elem.half_width
                #needed for outlines
                primitive_half_height = elem.half_height
            idx += 1

        if primitive_half_width == 0 and idx == utm_w:
            raise Exception(
                'No primitive were generated for the drawing of the wavescape')

        subpart_offset = 0
        if subparts_highlighted is not None:
            hl_dimensions = len(np.shape(subparts_highlighted))
            if hl_dimensions == 1 and len(subparts_highlighted) == 2:
                #restraining dimensions of what'll be drawn
                if subparts_highlighted[0] >= subparts_highlighted[1]:
                    raise Exception(
                        'subparts_highlighted coordinates should be ordered and not the same'
                    )
                elif subparts_highlighted[0] > utm_w or subparts_highlighted[
                        1] > utm_w:
                    raise Exception(
                        'subparts_highlighted coordinates should not exceed the matrix size (%d)'
                        % utm_w)

                start_primitive_idx = subparts_highlighted[0]
                utm_h = subparts_highlighted[1]
                utm_w = subparts_highlighted[1]

                #cannot work with this "mode"
                if indicator_size:
                    msg = "Vertical indicators cannot be drawn when subparts are being produced."
                    warn(msg)
                    indicator_size = None
                self.subparts = None

                #need to adapt start offset
                if aw_per_tick:
                    subpart_offset = -(start_primitive_idx % aw_per_tick)

            elif hl_dimensions == 2:
                #wavescape fullpart conserved, only has to draw highlights on it.
                self.subparts = subparts_highlighted
                #so the highlights are thicker than the delimiting lines
                linewidth = 2.5 * add_line if add_line else 1
                self.generate_highlights(primitive_half_width * 2, linewidth)
            else:
                raise Exception(
                    'subparts_highlighted should be a matrix of numeric values or a tuple of numbers'
                )
        else:
            self.subparts = None

        height = self.height
        width = self.width

        dpi = 96  #(most common dpi values for computers' screen)
        if not ax:
            fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi)
            ax = fig.add_subplot(111, aspect='equal')

        for y in range(utm_h):
            for x in range(start_primitive_idx + y, utm_w):
                element = self.matrix_primitive[y][x]
                #array of primitive is by default filled with None value, this avoid that.
                if element:
                    ax.add_patch(element.draw(stroke=add_line))

        if indicator_size:
            ind_width = (width if self.primitive != self.HEXAGON_STR else
                         width + 2) * indicator_size
            mid_size = int(ind_width / 60.)
            eigth_size = int(mid_size / 4.)
            quart_size = eigth_size * 3

            white_fill = (1, 1, 1, 0)
            middle_gray = (.398, .398, .398, 1)

            params = [{
                'size': mid_size,
                'facecolor': white_fill,
                'edgecolor': 'black'
            }, {
                'size': quart_size,
                'facecolor': white_fill,
                'edgecolor': middle_gray
            }, {
                'size': eigth_size,
                'facecolor': middle_gray,
                'edgecolor': middle_gray
            }]

            stroke_width = int(self.width / 1000.) + 1

            # Code to draw the indicators using circles.
            # This is probably the most far fetched discrete mathematical formula I ever made.
            # Basically I found the coordinates relative to the height and width of the plot by trial
            # and error using negative power of 2, and then I derived a discrete formula
            # depending on two parameters n and m (the second one depending on the first)
            # which give me automatically the right x and y coordinates. It works, just trust me.
            for n in range(1, 4):
                p = params[n - 1]
                for m in range(2**(n - 1)):
                    x = 1 / float(2**(n + 1)) + m / float(2**n)
                    y = (2**n - 1) / float(2**n) - m / float(2**
                                                             (n - 1)) - 1 / 2.
                    for i in [-1, 1]:
                        ax.add_patch(
                            Circle((i * x * width - primitive_half_width,
                                    y * height),
                                   radius=p['size'],
                                   facecolor=p['facecolor'],
                                   edgecolor=p['edgecolor'],
                                   linewidth=stroke_width))

        plt.autoscale(enable=True)

        if not aw_per_tick and not label and label_size:
            msg = "'label_size' argument provided when nothing needs to be labeled on the figure."
            warn(msg)

        labelsize = label_size if label_size else self.width / 30.

        if aw_per_tick:
            indiv_w = primitive_half_width * 2

            scale_x = indiv_w * aw_per_tick
            maj_loc_offset = (tick_offset + subpart_offset) * indiv_w

            major_ticks_formatter = lambda x, pos: '{0:g}'.format(
                (math.ceil((x + self.width / 2.) / scale_x) * tick_factor +
                 (0 if tick_offset < 1 else -1)) + tick_start)

            ticks_x = FuncFormatter(major_ticks_formatter)
            ax.tick_params(which='major',
                           length=self.width / 50.,
                           labelsize=labelsize)
            ax.tick_params(which='minor', length=self.width / 100.)

            ax.xaxis.set_major_formatter(ticks_x)
            number_of_ticks = self.width / scale_x
            number_of_bars = (utm_w - start_primitive_idx) / aw_per_tick
            major_tick_base = scale_x * round(
                number_of_ticks /
                (8 if number_of_bars > 8 else number_of_ticks))
            ax.xaxis.set_major_locator(
                IndexLocator(base=major_tick_base, offset=maj_loc_offset))

            #display minor indicators
            ax.xaxis.set_minor_locator(
                IndexLocator(base=scale_x, offset=maj_loc_offset))

            #make all the other border invisible
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)
            ax.spines['left'].set_visible(False)
            plt.yticks([])
        else:
            plt.axis('off')

        if self.subparts:
            for pat in self.subparts:
                ax.add_patch(pat)

        #whether a subwavescape is drawn will influence the values returned by this function.
        bb_l, bb_r, bb_t, bb_b = compute_bounding_box_limits(
            self.matrix_primitive.shape[0], start_primitive_idx, utm_w,
            self.width, self.height, primitive_half_width)

        #needed to account for line_width in the plot's size
        if add_line:
            bb_l += -add_line
            bb_r += add_line

        if label:
            new_width = np.abs(bb_l - bb_r)
            new_height = np.abs(bb_b - bb_t)
            x_pos = (new_width / 20.) + bb_l
            y_pos = bb_t - (new_height / 20.)
            ax.annotate(label, (x_pos, y_pos),
                        size=labelsize,
                        annotation_clip=False,
                        horizontalalignment='left',
                        verticalalignment='top')

        #remove top and bottom margins
        ax.set_ylim(bottom=bb_b, top=bb_t)
        ax.set_xlim(left=bb_l, right=bb_r)
        plt.tight_layout()
Ejemplo n.º 25
0
def heatmap_up_dict(up_dic,
                    plot_lims=None,
                    title='XX',
                    ax=None,
                    fig=None,
                    diff=False,
                    ticklabel=True,
                    legend=True,
                    ticks_step=10):
    if plot_lims is None:
        x, y = list(up_dic.keys()), list(up_dic.values())
    else:
        x, y = list(up_dic.keys())[plot_lims[0]:plot_lims[1] + 1], list(
            up_dic.values())[plot_lims[0]:plot_lims[1] + 1]
    print(len(x), len(y))
    if (len(x) > 200):
        print("Skipping heatmap, sequence longer than 200 limit. < {} ".format(
            len(x)))
        return

    if ax is None:
        ax = fig.add_subplot(121)
    ax.yaxis.set_label_position("right")

    # Now adding the colorbar
    #     pos1 = ax.get_position() # get the original position
    #     pos2 = [pos1.x0 + 0.3, pos1.y0 + 0.3,  pos1.width / 2.0, pos1.height / 2.0]
    if legend:
        cax = fig.add_axes([1.0, 0.5, 0.1, .1])
    else:
        cax = None

#     ax.plot(x, y, label=title)
#     sns.pointplot(x,y,ax=ax)
    ax.set_xticks(np.arange(min(x) - min(x) % ticks_step, max(x), ticks_step))
    ax.set_yticks(np.arange(min(y) - min(y) % ticks_step, max(y), ticks_step))

    sns.heatmap(
        np.reshape(np.array(y), (len(y), 1)),
        cmap=sns.cubehelix_palette(as_cmap=True),
        ax=ax,
        cbar=legend,
        cbar_ax=cax,
        vmin=0.0,
        vmax=1.0,
        # yticklabels=x,
    )
    #     cbar = ax.collections[0].colorbar
    #     cbar.set_ticks([0., .2, .4, .6, .8, 1.0])

    #     cbar.set_ticklabels(['low', '20%', '75%', '100%'])
    if legend:
        ax.legend(loc='upper left')  #, bbox_to_anchor=(0.0, 1.1))

    minor_ticks = np.arange(min(x), max(x), 1)
    major_ticks = np.arange(min(x) - min(x) % 10, max(x), 10)
    yticks = x
    keptticks = yticks[::10]
    yticks = ['' for y in yticks]
    yticks[::10] = keptticks
    #     ax.set_yticks(minor_ticks,                   minor=True)
    from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FormatStrFormatter, FuncFormatter, IndexLocator, StrMethodFormatter
    minorLocator = IndexLocator(1, offset=0.5)
    majorLocator = IndexLocator(10, offset=0.5)

    def incer(x, pos):
        'The two args are the value and tick position'
        return '%d' % (x + 1)

    majorFormatter = FuncFormatter(incer)
    #     majorFormatter = StrMethodFormatter('{x}',use_offset=False                                       )

    #     ax.set_yticklabels(yticks, rotation=0,)

    ax.yaxis.set_minor_locator(minorLocator)
    ax.yaxis.set_major_locator(majorLocator)
    ax.tick_params(which='major', length=6)
    ax.tick_params(which='minor', length=3)
    if ticklabel:
        ax.yaxis.set_major_formatter(majorFormatter)
        #         ax.set_yticklabels(yticks, rotation=0,)

        #         ax.tick_params(which='minor', length=6)

        ax.yaxis.set_label_position("right")
    else:
        ax.set_yticklabels([])
#     ax.set_yticks(major_ticks)
#     ax.set_ylabel('Position')
#     ax.set_yticks([-1, 1], minor=False, )

    if diff:
        ax.set_xticks([-1, 1], minor=True)
        ax.set_xlim([-1.05, 1.05])
        ax.set_xlabel('P_unpaired(wild) - P_unpaired(mut)')
    else:
        ax.set_xticks(
            [],
            minor=False,
        )


#         ax.set_xlim([-0.05,1.05])
#         ax.set_xlabel('Accessibility')
#     ax.grid(which='both')

# or if you want differnet settings for the grids:
#     ax.grid(which='minor', alpha=0.5)
#     ax.axhline(0, linestyle='--', color='k', alpha=0.5) # horizontal lines
#     ax.axhline(1, linestyle='--', color='k', alpha=0.5) # horizontal lines

#     ax.set_ylim([min(x)-1, max(x)+1])
    ax.set_title(title, rotation=90, va='bottom')