Exemplo n.º 1
0
def plot_optimal_rpm_region(ax: matplotlib.axes, plot_data: pd.PlotData):

    optimal_rpm, optimal_rpm_range_min, optimal_rpm_range_max = data_processing.get_optimal_rpm(plot_data=plot_data)
    if optimal_rpm is not None:
        ax.axvline(optimal_rpm, color='green', alpha=0.5)
    if optimal_rpm_range_min is not None and optimal_rpm_range_max is not None:
        ax.axvspan(optimal_rpm_range_min, optimal_rpm_range_max, color='green', alpha=0.25)
Exemplo n.º 2
0
 def makeSpeedVsHeadDirectionPlot(self, spk_times: np.array,
                                  ax: matplotlib.axes = None,
                                  **kwargs) -> matplotlib.axes:
     self.initialise()
     spk_times_in_pos_samples = self.getSpikePosIndices(spk_times)
     idx = np.array(spk_times_in_pos_samples, dtype=int)
     if np.ma.is_masked(self.speed):
         w = self.speed.mask
         w = np.array(~w, dtype=int)
     else:
         w = np.bincount(idx, minlength=self.speed.shape[0])
     dir_bins = np.arange(0, 360, 6)
     spd_bins = np.arange(0, 30, 1)
     h = np.histogram2d(
         self.dir, self.speed, [dir_bins, spd_bins], weights=w)
     from ephysiopy.common.utils import blurImage
     im = blurImage(h[0], 5, ftype='gaussian')
     im = np.ma.MaskedArray(im)
     # mask low rates...
     im = np.ma.masked_where(im <= 1, im)
     # ... and where less than 0.5% of data is accounted for
     x, y = np.meshgrid(dir_bins, spd_bins)
     vmax = np.max(np.ravel(im))
     if ax is None:
         fig = plt.figure()
         ax = fig.add_subplot(111)
     ax.pcolormesh(x, y, im.T, cmap=plt.cm.get_cmap("jet"),
                   edgecolors='face',
                   vmax=vmax, shading='auto')
     plt.xticks([90, 180, 270], fontweight='normal', size=6)
     plt.yticks([10, 20], fontweight='normal', size=6)
     return ax
Exemplo n.º 3
0
def force_aspect(ax: mpl.axes, aspect: int = 1):
    '''
    Forces the aspect of the axes object `ax`.
    '''
    im = ax.get_images()
    extent = im[0].get_extent()
    ax.set_aspect(
        abs((extent[1] - extent[0]) / (extent[3] - extent[2])) / aspect)
Exemplo n.º 4
0
def evolution_of_participation_1D(
    data: dict,
    ax: mpl.axes,
    entity_in_focus: Optional[list] = None,
    percentage: bool = False,
    colormap: mpl.colors.LinearSegmentedColormap = mpl.cm.jet,
) -> mpl.axes:
    """
    Parameters
    ----------
    data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}}
    entity_in_focus :
    percentage :
    """
    x = list(data.keys())
    ylabels = stackedareachart.get_ylabels(data)
    y = stackedareachart.data_transformation(data, ylabels, percentage)
    colors = utils.create_color_palette(
        ylabels,
        entity_in_focus,
        colormap,
        include_dof=False,
        return_dict=True,
    )
    for iy, ylab in enumerate(ylabels):
        if ylab in entity_in_focus:
            ax.plot(
                x,
                y[iy, :],
                color="w",
                linewidth=4,
                zorder=1,
            )
            ax.plot(
                x,
                y[iy, :],
                color=colors[ylab],
                linewidth=3,
                zorder=1,
                label=ylab,
            )
        else:
            ax.plot(
                x,
                y[iy, :],
                color="grey",
                linewidth=1,
                zorder=0,
                alpha=0.2,
            )
    if np.isfinite(np.max(x)):
        ax.set_xlim(np.min(x), np.max(x))
    if np.isfinite(np.max(y)):
        ax.set_ylim(np.min(y), np.max(y))
    return ax
Exemplo n.º 5
0
def plotTTPMat(ax: axes,
               toa: np.array,
               ttp: np.array,
               title: str = None,
               plot_ylabel: bool = False) -> None:
    ax.scatter(toa, ttp, marker='o', c=ttp, alpha=0.75)
    ax.set_ylim(PRI_DETECTED_RANGE[0], PRI_DETECTED_RANGE[1])
    ax.xaxis.get_major_formatter().set_powerlimits((0, 1))
    ax.set_title(title, fontsize=10)
    ax.set_xlabel('toa[us]', fontsize=8, loc='right')
    if plot_ylabel:
        ax.set_ylabel('pri[us]', fontsize=9)
Exemplo n.º 6
0
def format_axes(in_ax: matplotlib.axes,
                labelsize: int = 12,
                ticksize: int = 10,
                legendsize: int = 8,
                box: bool = False) -> None:
    """Formats ticks, tick label sizes, and axes label sizes for box plots.

    Parameters
    ----------
    in_ax : matplotlib.axes
        Axes containing a plot.
    labelsize : int, optional
        Size of axes labels.
    ticksize : int, optional
        Size of tick labels.
    legendsize : int, optional
        Specifies font size of strings in legend.
    box : bool, optional
        Specifies whether or not a box plot has been plotted.

    Returns
    -------
    None
    """
    in_ax.xaxis.set_minor_locator(AutoMinorLocator())
    in_ax.yaxis.set_minor_locator(AutoMinorLocator())
    in_ax.xaxis.label.set_size(labelsize)
    in_ax.yaxis.label.set_size(labelsize)
    in_ax.tick_params(axis='both',
                      which='major',
                      direction='in',
                      length=4,
                      bottom=True,
                      top=True,
                      left=True,
                      right=True,
                      labelsize=ticksize,
                      color='grey')
    in_ax.tick_params(axis='both',
                      which='minor',
                      direction='in',
                      length=2,
                      bottom=True,
                      top=True,
                      left=True,
                      right=True,
                      color='grey')
    if not box:
        legend = in_ax.legend(fontsize=legendsize,
                              edgecolor=(1, 1, 1, 0.),
                              facecolor=(1, 1, 1, 0))
        legend.get_frame().set_alpha(0)
Exemplo n.º 7
0
def make_stats_plot(cohort_averages: dict,
                    observable: str,
                    in_ax: matplotlib.axes,
                    geo: bool = False,
                    labelsize: int = 12,
                    ticksize: int = 10,
                    legendsize: int = 8,
                    box=False) -> None:
    """Plots an observable for all cohorts on a single axes object.

    Parameters
    ----------
    cohort_averages : dict
        Dictionary of averages and variations within a cohort for all severities.
    observable : str
        The quantity which is going to be plotted.
    in_ax : matplotlib.axes
        The axes on which values are going to be plotted.
    geo: bool, optional
        Specifies geometric or arithmetic averaging.
    labelsize : int, optional
        Size of axes labels.
    ticksize : int, optional
        Size of tick labels.
    legendsize : int, optional
        Specifies font size of strings in legend.
    box : bool, optional
        Specifies whether or not a box plot has been plotted.

    Returns
    -------
    None
    """

    cohort_plot(cohort_averages, observable, in_ax=in_ax, geo=geo)

    #  Name of xlabel for each observable.
    xlabels = {
        'cdr3 length': 'HCDR3 length [aa]',
        'vd ins': 'VD insertions [nt]',
        'vd del': 'VD deletions [nt]',
        'dj ins': 'DJ insertions [nt]',
        'dj del': 'DJ deletions [nt]'
    }
    in_ax.set_xlabel(xlabels[observable], fontname="Arial")
    in_ax.set_ylabel("relative counts", family="Arial")
    format_axes(in_ax,
                labelsize=labelsize,
                ticksize=ticksize,
                legendsize=legendsize,
                box=False)
Exemplo n.º 8
0
    def makeSpeedVsRatePlot(
            self, spk_times: np.array, minSpeed: float = 0.0,
            maxSpeed: float = 40.0, sigma: float = 3.0,
            ax: matplotlib.axes = None, **kwargs) -> matplotlib.axes:
        """
        Plots the instantaneous firing rate of a cell against running speed
        Also outputs a couple of measures as with Kropff et al., 2015; the
        Pearsons correlation and the depth of modulation (dom) - see below for
        details
        """
        self.initialise()
        spk_times_in_pos_samples = self.getSpikePosIndices(spk_times)

        speed = np.ravel(self.speed)
        if np.nanmax(speed) < maxSpeed:
            maxSpeed = np.nanmax(speed)
        spd_bins = np.arange(minSpeed, maxSpeed, 1.0)
        # Construct the mask
        speed_filt = np.ma.MaskedArray(speed)
        speed_filt = np.ma.masked_where(speed_filt < minSpeed, speed_filt)
        speed_filt = np.ma.masked_where(speed_filt > maxSpeed, speed_filt)
        from ephysiopy.common.spikecalcs import SpikeCalcsGeneric

        x1 = spk_times_in_pos_samples
        S = SpikeCalcsGeneric(x1)
        spk_sm = S.smoothSpikePosCount(x1, self.xyTS.shape[0], sigma, None)
        spk_sm = np.ma.MaskedArray(spk_sm, mask=np.ma.getmask(speed_filt))
        spd_dig = np.digitize(speed_filt, spd_bins, right=True)
        mn_rate = np.array([np.ma.mean(
            spk_sm[spd_dig == i]) for i in range(0, len(spd_bins))])
        var = np.array([np.ma.std(
            spk_sm[spd_dig == i]) for i in range(0, len(spd_bins))])
        np.array([np.ma.sum(
            spk_sm[spd_dig == i]) for i in range(0, len(spd_bins))])
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.errorbar(
            spd_bins, mn_rate * self.pos_sample_rate,
            yerr=var, color='k')
        ax.set_xlim(spd_bins[0], spd_bins[-1])
        plt.xticks([spd_bins[0], spd_bins[-1]], ['0', '{:.2g}'.format(
            spd_bins[-1])], fontweight='normal', size=6)
        plt.yticks([0, np.nanmax(
            mn_rate)*self.pos_sample_rate], ['0', '{:.2f}'.format(
                np.nanmax(mn_rate))], fontweight='normal', size=6)
        return ax
Exemplo n.º 9
0
def plotPRITransformVal(ax: axes,
                        bins: np.array,
                        vals: np.array,
                        title: str = None,
                        plot_ylabel: bool = False) -> None:
    ax.plot(bins, vals, linewidth=2)
    ax.set_title(title, fontsize=10)
    ax.set_xlabel('pri[us]', fontsize=8, loc='right')
    if plot_ylabel:
        ax.set_ylabel('interval values', fontsize=10)
Exemplo n.º 10
0
 def makeRateMap(self, spk_times: np.array,
                 ax: matplotlib.axes = None) -> matplotlib.axes:
     self.initialise()
     spk_times_in_pos_samples = self.getSpikePosIndices(spk_times)
     spk_weights = np.bincount(
         spk_times_in_pos_samples, minlength=self.npos)
     rmap = self.RateMapMaker.getMap(spk_weights)
     ratemap = np.ma.MaskedArray(rmap[0], np.isnan(rmap[0]), copy=True)
     x, y = np.meshgrid(rmap[1][1][0:-1], rmap[1][0][0:-1])
     vmax = np.nanmax(np.ravel(ratemap))
     if ax is None:
         fig = plt.figure()
         ax = fig.add_subplot(111)
     ax.pcolormesh(
         x, y, ratemap, cmap=plt.cm.get_cmap("jet"), edgecolors='face',
         vmax=vmax, shading='auto')
     ax.set_aspect('equal')
     return ax
Exemplo n.º 11
0
def plot_vertical_line(
    plot: matplotlib.axes,
    line_name: str,
    line_value: float,
    list_of_colors: List[str],
    num_for_color: int,
):
    """"""

    import numpy

    plot.axvline(
        x=line_value,
        label=f"{line_name} - {numpy.round(line_value, 2)}",
        c=list_of_colors[num_for_color],
        lw=0.6,
        ls="--",
    )
Exemplo n.º 12
0
def _plotIDStrip(ax: matplotlib.axes, id_array: np.ndarray, label: str,
                 x_extents: List[float]) -> None:
    '''
    Plot a strip above the data sequence image that represents class labels at each time.
    '''

    id_array = np.reshape(id_array, (1, len(id_array)))
    ax.imshow(id_array, aspect="auto", interpolation="none", extent=x_extents + [0, 1])
    ax.set_ylabel(label)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_ticks([])
Exemplo n.º 13
0
def stacked_area_chart(
    data: dict,
    ax: mpl.axes,
    domains_in_focus: Optional[list] = None,
    percentage: bool = False,
    colormap: Optional[mpl.colors.LinearSegmentedColormap] = None,
    color_default: Optional[np.array] = None,
):
    """
    Parameters
    ----------
    data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}}
    domains_in_focus :
    percentage :
    """
    x = list(data.keys())
    y = data_transformation(data, percentage)
    ylabels = get_ylabels(data)
    colors = utils.create_color_palette(
        ylabels,
        domains_in_focus,
        colormap,
        include_dof=True,
        return_dict=False,
    )
    ax.stackplot(
        x,
        y,
        colors=colors,
    )
    ax.set_xlim(np.min(x), np.max(x))
    ax.set_ylim(np.min(y), np.max(y))
    return ax
Exemplo n.º 14
0
def highlight_base(
    pos_highlight: int, seq: SeqRecord, ax: mpl.axes, passed_filter=True
) -> mpl.axes:
    """Highlight the area around a peak with a rectangle."""

    peaks = seq.annotations["peak positions"]
    peak = peaks[pos_highlight - 1]

    xmin, xmax = ax.get_xlim()
    if not xmin <= peak < xmax:
        raise ValueError("peak not within plot bounds")

    if pos_highlight == 1:
        xmin = -0.5
    else:
        xmin = 0.5 * (peaks[pos_highlight - 1] + peaks[pos_highlight - 2])

    if pos_highlight == len(peaks):
        xmax = -0.5
    else:
        xmax = 0.5 * (peaks[pos_highlight - 1] + peaks[pos_highlight])
    ymin, ymax = ax.get_ylim()

    if passed_filter:
        fcolor = "yellow"
    else:
        fcolor = "grey"
    rec = mpl.patches.Rectangle(
        (xmin, ymin),
        (xmax - xmin),
        (ymax - ymin),
        edgecolor="none",
        facecolor=fcolor,
        alpha=0.3,
    )
    ax.add_patch(rec)
    return ax
Exemplo n.º 15
0
def plot_openness(data: list, period: dict, ax: Axes):
    """
    Plots the openness from the raw data.

    :param data: Raw data
    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    # Get data
    datetimes, openness = get_openness(data, period)

    # Make filled line plot
    ax.fill_between(datetimes, openness)

    # Decorate axes
    ax.xaxis.set_major_locator(MonthLocator((1, 4, 7, 10), bymonthday=1))
    ax.xaxis.set_major_formatter(DateFormatter("%b '%y"))
    ax.set_yticklabels([f"{o * 100:.0f}{percent()}" for o in ax.get_yticks()])
    ax.set_ylabel("Andel åpen")
    ax.grid(linestyle="-.")
Exemplo n.º 16
0
def _draw_outer_border(ax: axes, xmin, xmax, ymin, ymax, **kwargs):
    """
    Fill the right upper corner of a diagram, everything beyond (xmin, ymin).

    The following graphic shows the filled regions with dots:

          ↑
    ymax  +..............
          |..............
    ymin  +..............
          |       .......
          |       .......
          +-------+-----+-→
                xmin   xmax
    """
    verts = [(xmin, ymin), (xmin, 0), (xmax, 0), (xmax, ymax), (0, ymax),
             (0, ymin)]
    return ax.add_patch(Polygon(np.array(verts), **kwargs))
Exemplo n.º 17
0
def show_reference(
    query_record: SeqRecord,
    subject_record: SeqRecord,
    ax: mpl.axes,
    ref_central: Optional[int] = None,
) -> mpl.axes:
    """show the reference of the chromatograph.

    design: if location is not proviode, do the alignment first
    @param seq: input SeqRecord of ref
    """

    sitepairs = align_chromatograph(
        query_record, subject_record, ignore_ambig=True
    )
    sitepairs_indexing = {s.cf_pos: s for s in sitepairs}
    cf_sites = [int(i.get_text()) for i in ax.get_xticklabels()]
    matched_sitepairs = [sitepairs_indexing[pos] for pos in cf_sites]
    for i, peak in enumerate(ax.get_xticks()):
        ax.text(
            peak,
            1.05,
            matched_sitepairs[i].ref_base,
            color="dimgrey",
            va="bottom",
            ha="center",
            alpha=0.85,
            fontsize="xx-large",
            fontweight="bold",
            clip_on=False,
        )
        if ref_central is not None:
            ref_pos = matched_sitepairs[i].ref_pos - ref_central
        else:
            ref_pos = matched_sitepairs[i].ref_pos
        ax.text(
            peak,
            1.12,
            ref_pos,
            color="dimgrey",
            va="bottom",
            ha="center",
            alpha=0.85,
            fontsize="medium",
            fontweight="normal",
            clip_on=False,
        )
    return ax
Exemplo n.º 18
0
 def makeSpikePathPlot(self, spk_times: np.array = None,
                       ax: matplotlib.axes = None,
                       **kwargs) -> matplotlib.axes:
     self.initialise()
     if 'c' in kwargs:
         col = kwargs.pop('c')
     else:
         col = tcols.colours[1]
     if ax is None:
         fig = plt.figure()
         ax = fig.add_subplot(111)
     ax.plot(self.xy[0, :], self.xy[1, :], c=tcols.colours[0], zorder=1)
     ax.set_aspect('equal')
     if spk_times is not None:
         idx = self.getSpikePosIndices(spk_times)
         ax.plot(
             self.xy[0, idx], self.xy[1, idx], 's', c=col, **kwargs)
     return ax
Exemplo n.º 19
0
def evolution_of_participation_2D(
    xdata: dict,
    ydata: dict,
    ax: mpl.axes,
    entity_in_focus: Optional[list] = None,
    percentage: bool = False,
    colormap: mpl.colors.LinearSegmentedColormap = mpl.cm.jet,
) -> mpl.axes:
    """
    Parameters
    ----------
    data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}}
    entity_in_focus :
    percentage :
    """
    # TODO: include time indication
    xlabels = stackedareachart.get_ylabels(xdata)
    ylabels = stackedareachart.get_ylabels(ydata)
    # ensure uniform order
    labels = list(set(xlabels + ylabels))
    xindx = [xlabels.index(lab) if lab in xlabels else None for lab in labels]
    xlabels = [xlabels[i] if i is not None else None for i in xindx]
    yindx = [ylabels.index(lab) if lab in ylabels else None for lab in labels]
    ylabels = [ylabels[i] if i is not None else None for i in yindx]
    # create arrays with format (# of ylabels, # of xlabels)
    x = stackedareachart.data_transformation(xdata, xlabels, percentage)
    y = stackedareachart.data_transformation(ydata, ylabels, percentage)
    colors = utils.create_color_palette(
        ylabels,
        entity_in_focus,
        colormap,
        include_dof=False,
        return_dict=True,
    )
    ax.plot([0, np.max(y)], [0, np.max(y)], c="k", linestyle="--", zorder=0)
    for i, lab in enumerate(labels):
        if lab in entity_in_focus:
            ax.plot(
                x[i, :],
                y[i, :],
                color="w",
                linewidth=4,
                zorder=1,
            )
            ax.plot(
                x[i, :],
                y[i, :],
                color=colors[lab],
                linewidth=3,
                zorder=1,
                label=lab,
            )
        else:
            ax.plot(
                x[i, :],
                y[i, :],
                color="grey",
                linewidth=1,
                zorder=0,
                alpha=0.2,
            )
    ax.set_xlim(np.min(x), np.max(x))
    ax.set_ylim(np.min(y), np.max(y))
    return ax
Exemplo n.º 20
0
def plot_kdeplot(data: List[np.float64], axes: matplotlib.axes):
    sns.kdeplot(data=data, kernel='gau', bw='scott', ax=axes)
    axes.set_title('KDE plot')
    axes.set_xlabel('x')
    axes.set_ylabel('f')
Exemplo n.º 21
0
def cohort_bar(cohort_averages: dict,
               cohort_data: dict,
               observable: str,
               yaxis_upper: int = None,
               ax: matplotlib.axes = None,
               labelsize: int = 12,
               ticksize: int = 10,
               legendsize: int = 8,
               markersize=15) -> None:
    """Plots either the V- or J-gene usages.

    Parameters
    ----------
    cohort_averages : dict
        Dictionary of averages and variations within a cohort for all severities.
    cohort_dict : dict
        Dictionary of all statistics of all individuals in a cohort for all severities.
    observable : str
        The quantity which is going to be plotted.
    yaxis_upper : int, optional
        Specifies the upper limit of the y-axis on the plot.
    ax : matplotlib.axes, optional
        Used to modify an already existing axes when creating a figure with a grid.
    labelsize : int, optional
        Size of axes labels.
    ticksize : int, optional
        Size of tick labels.
    legendsize : int, optional
        Specifies font size of strings in legend.

    Returns
    -------
    None
    """

    if ax is None:
        fig = plt.figure(dpi=300, figsize=(16, 4))
        ax = fig.add_subplot(111)

    #  Give the bars for each gene some space among each other.
    width = 1.0 / len(cohort_averages) - 0.02
    bars = []

    if 'Asymptomatic' in cohort_averages:
        ordering = ['Healthy', 'Mild', 'Moderate', 'Severe', 'Asymptomatic']
    else:
        ordering = sorted(cohort_averages.keys())

    #  Sort the genes by descending usage in the healthy cohort.
    if 'Briney/GRP' in cohort_averages:
        sorted_genes = [
            gene for _, gene in sorted(zip(
                cohort_averages['Briney/GRP'][observable][0],
                cohort_averages['Briney/GRP'][observable][-1]),
                                       key=lambda pair: pair[0],
                                       reverse=True)
        ]
    else:
        sorted_genes = [
            gene for _, gene in sorted(zip(
                cohort_averages['Healthy'][observable][0],
                cohort_averages['Healthy'][observable][-1]),
                                       key=lambda pair: pair[0],
                                       reverse=True)
        ]

    #  Because there are so many V genes, plot only those which have at least
    #  1% average usage in at least one cohort.
    if 'v' in observable:
        good_genes = []
        for gene in sorted_genes:
            bools = 0
            for severity in cohort_averages:
                idx = cohort_averages[severity][observable][-1].index(gene)
                value = cohort_averages[severity][observable][0][idx]
                bools += value >= 0.01
            if bools != 0:
                good_genes.append(gene)
    else:
        good_genes = sorted_genes

    xlabels = good_genes
    default_x = np.arange(0, len(good_genes), 1)
    xs, ys = [], []
    for i, severity in enumerate(ordering):
        x = default_x + width * i
        xs.append(x)
        indices = [
            cohort_averages[severity][observable][-1].index(gene)
            for gene in good_genes
        ]
        y = [cohort_averages[severity][observable][0][k] for k in indices]
        ys.append(y)

    if observable == 'v gene':
        ax.set_xlim(-0.3, xs[0][-1] + 1.0)
        if yaxis_upper is not None:
            ax.set_ylim(0, yaxis_upper)
        else:
            ax.set_ylim(0, 0.35)
    else:
        ax.set_xlim(-0.3, xs[0][-1] + 1.0)
        if yaxis_upper is not None:
            ax.set_ylim(0, yaxis_upper)
        else:
            ax.set_ylim(0, 0.55)

    #  Specifiy location of xticks as being in the middle of the grouping of bars.
    middle = np.mean(np.arange(0, len(cohort_averages)))
    middle_xticks = default_x + middle * width
    ax.set_xticks(middle_xticks)
    ax.set_xticklabels(xlabels, rotation=90, family='Arial')
    ax.set_ylabel('relative counts', fontname="Arial")

    #  Plot the bars.
    for i, severity in enumerate(ordering):
        bar = ax.bar(xs[i],
                     ys[i],
                     width,
                     color=colors[severity],
                     label=severity)
        for d in cohort_data[severity][observable]:
            #  Plot the full distributions of values to get a better sense
            #  of variation within cohorts.
            for gidx, rect in enumerate(bar):
                ax.scatter(xs[i][gidx],
                           d[good_genes[gidx]],
                           marker='.',
                           color=lightercolors[severity],
                           zorder=3,
                           s=markersize,
                           edgecolors='black',
                           linewidths=0.3)

    format_axes(ax,
                labelsize=labelsize,
                ticksize=ticksize,
                legendsize=legendsize)
Exemplo n.º 22
0
    def show_SAC(self, A: np.array, inDict: dict,
                 ax: matplotlib.axes = None, **kwargs) -> matplotlib.axes:
        """
        Displays the result of performing a spatial autocorrelation (SAC)
        on a grid cell.

        Uses the dictionary containing measures of the grid cell SAC to
        make a pretty picture

        Parameters
        ----------
        A : array_like
            The spatial autocorrelogram
        inDict : dict
            The dictionary calculated in getmeasures
        ax : matplotlib.axes._subplots.AxesSubplot, optional
            If given the plot will get drawn in these axes. Default None

        Returns
        -------
        fig : matplotlib.Figure instance
            The Figure on which the SAC is shown

        See Also
        --------
        ephysiopy.common.binning.RateMap.autoCorr2D()
        ephysiopy.common.ephys_generic.FieldCalcs.getMeaures()
        """
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        Am = A.copy()
        Am[~inDict['dist_to_centre']] = np.nan
        Am = np.ma.masked_invalid(np.atleast_2d(Am))
        x, y = np.meshgrid(
            np.arange(0, np.shape(A)[1]),
            np.arange(0, np.shape(A)[0]))
        vmax = np.nanmax(np.ravel(A))
        ax.pcolormesh(
            x, y, A, cmap=plt.cm.get_cmap("gray_r"),
            edgecolors='face', vmax=vmax, shading='auto')
        import copy
        cmap = copy.copy(plt.cm.get_cmap("jet"))
        cmap.set_bad('w', 0)
        ax.pcolormesh(
            x, y, Am, cmap=cmap,
            edgecolors='face', vmax=vmax, shading='auto')
        # horizontal green line at 3 o'clock
        _y = (np.shape(A)[0]/2, np.shape(A)[0]/2)
        _x = (np.shape(A)[1]/2, np.shape(A)[0])
        ax.plot(_x, _y, c='g')
        mag = inDict['scale'] * 0.5
        th = np.linspace(0, inDict['orientation'], 50)
        from ephysiopy.common.utils import rect
        [x, y] = rect(mag, th, deg=1)
        # angle subtended by orientation
        ax.plot(
            x + (inDict['dist_to_centre'].shape[1] / 2),
                (inDict['dist_to_centre'].shape[0] / 2) - y, 'r', **kwargs)
        # plot lines from centre to peaks above middle
        for p in inDict['closest_peak_coords']:
            if p[0] <= inDict['dist_to_centre'].shape[0] / 2:
                ax.plot(
                    (inDict['dist_to_centre'].shape[1]/2, p[1]),
                    (inDict['dist_to_centre'].shape[0] / 2, p[0]), 'k', **kwargs)
        ax.invert_yaxis()
        all_ax = ax.axes
        all_ax.set_aspect('equal')
        all_ax.set_xlim((0.5, inDict['dist_to_centre'].shape[1]-1.5))
        all_ax.set_ylim((inDict['dist_to_centre'].shape[0]-.5, -.5))
        return ax
Exemplo n.º 23
0
def evolution_of_graph_property_by_domain(
    data: dict,
    xkey: str,
    ykey: str,
    ax: mpl.axes,
    entity_in_focus: Optional[list] = None,
    percentile: Optional[float] = None,
    colormap: mpl.colors.LinearSegmentedColormap = mpl.cm.jet,
) -> mpl.axes:
    """
    Parameters
    ----------
        data : Dictionary create with
            bigbang.analysis.ListservList.get_graph_prop_per_domain_per_year()
        ax :
        entity_in_focus :
        percentile :
    """
    colors = utils.create_color_palette(
        list(data.keys()),
        entity_in_focus,
        colormap,
        include_dof=False,
        return_dict=True,
    )
    if entity_in_focus:
        for key, value in data.items():
            if key in entity_in_focus:
                ax.plot(
                    value[xkey],
                    value[ykey],
                    color="w",
                    linewidth=4,
                    zorder=1,
                )
                ax.plot(
                    value[xkey],
                    value[ykey],
                    color=colors[key],
                    linewidth=3,
                    label=key,
                    zorder=2,
                )
            else:
                ax.plot(
                    value[xkey],
                    value[ykey],
                    color="grey",
                    alpha=0.2,
                    linewidth=1,
                    zorder=0,
                )
    if percentile is not None:
        betweenness_centrality = []
        for key, value in data.items():
            betweenness_centrality += value[ykey]
        betweenness_centrality = np.array(betweenness_centrality)
        threshold = np.percentile(betweenness_centrality, percentile)

        for key, value in data.items():
            if any(np.array(value[ykey]) > threshold):
                ax.plot(
                    value[xkey],
                    value[ykey],
                    color="w",
                    linewidth=4,
                    zorder=1,
                )
                ax.plot(
                    value[xkey],
                    value[ykey],
                    linewidth=3,
                    color=colors[key],
                    label=key,
                    zorder=2,
                )
            else:
                ax.plot(
                    value[xkey],
                    value[ykey],
                    color="grey",
                    linewidth=1,
                    alpha=0.2,
                    zorder=0,
                )
    return ax
Exemplo n.º 24
0
 def makeXCorr(self, spk_times: np.array, ax: matplotlib.axes = None,
               **kwargs) -> matplotlib.axes:
     # spk_times in samples provided in seconds but convert to
     # ms for a more display friendly scale
     spk_times = spk_times / 3e4 * 1000.
     S = SpikeCalcsGeneric(spk_times)
     y = S.xcorr(spk_times)
     if ax is None:
         fig = plt.figure()
         ax = fig.add_subplot(111)
     ax.hist(
             y[y != 0], bins=201, range=[-500, 500],
             color='k', histtype='stepfilled')
     ax.set_xlim(-500, 500)
     ax.set_xticks((-500, 0, 500))
     ax.set_xticklabels('')
     ax.tick_params(
         axis='both', which='both', left=False, right=False,
         bottom=False, top=False)
     ax.set_yticklabels('')
     ax.spines['right'].set_visible(False)
     ax.spines['top'].set_visible(False)
     ax.spines['left'].set_visible(False)
     ax.xaxis.set_ticks_position('bottom')
     return ax
Exemplo n.º 25
0
 def makePowerSpectrum(
         self, freqs: np.array, power: np.array, sm_power: np.array,
         band_max_power: float, freq_at_band_max_power: float,
         max_freq: int = 50, theta_range: tuple = [6, 12],
         ax: matplotlib.axes = None, **kwargs) -> matplotlib.axes:
     # downsample frequencies and power
     freqs = freqs[0::50]
     power = power[0::50]
     sm_power = sm_power[0::50]
     if ax is None:
         fig = plt.figure()
         ax = fig.add_subplot(111)
     ax.plot(freqs, power, alpha=0.5, color=[0.8627, 0.8627, 0.8627])
     ax.plot(freqs, sm_power)
     ax.set_xlim(0, max_freq)
     ylim = [0, band_max_power / 0.8]
     if 'ylim' in kwargs:
         ylim = kwargs['ylim']
     ax.set_ylim(ylim)
     ax.set_ylabel('Power')
     ax.set_xlabel('Frequency')
     ax.text(
         x=theta_range[1] / 0.9, y=band_max_power,
         s=str(freq_at_band_max_power)[0:4], fontsize=20)
     from matplotlib.patches import Rectangle
     r = Rectangle((
         theta_range[0], 0), width=np.diff(theta_range)[0],
         height=np.diff(ax.get_ylim())[0], alpha=0.25, color='r', ec='none')
     ax.add_patch(r)
     return ax
Exemplo n.º 26
0
def plot_openness_by_weekday(data: list, period: dict, ax: Axes):
    """
    Plot the openness by weekday from the raw data.

    :param data: Raw data
    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    week_bins = get_openness_by_weekday(data, period)
    weekday_avg = sum(week_bins[0:5]) / 5
    weekend_avg = sum(week_bins[5:7]) / 2

    # Plot bar
    ax.bar(range(7), week_bins)

    # Plot averages
    ax.text(
        2,
        weekday_avg * 1.05,
        f"Gjennomsnitt ukedager: {weekday_avg * 100:.0f}{percent()}",
    )
    ax.text(
        4.5,
        weekend_avg * 1.1,
        f"Gjennomsnitt helgedager: {weekend_avg * 100:.0f}{percent()}",
    )
    ax.plot((0, 5 - 1), (weekday_avg, weekday_avg), "k--")
    ax.plot((5, 7 - 1), (weekend_avg, weekend_avg), "k--")

    # Decorate axes
    ax.set_xticklabels(
        ("", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag")
    )
    ax.set_yticklabels(
        [f"{openness * 100:.1f}{percent()}" for openness in ax.get_yticks()]
    )
    ax.set_ylabel("Andel åpen")
Exemplo n.º 27
0
def plot_chromatograph(
    seq: SeqRecord, region: Tuple[int, int] = None, ax: mpl.axes = None
) -> plt.axes:
    """Plot Sanger chromatograph.

    region: include both start and end (1-based)
    """
    if seq is None:
        return ax

    if region is None:
        # turn into 0 based for better indexing
        region_start, region_end = 0, len(seq)
    else:
        region_start = max(region[0], 0)
        region_end = min(region[1], len(seq) - 1)

    if ax is None:
        _, ax = plt.subplots(1, 1, figsize=(16, 6))

    _colors = defaultdict(
        lambda: "purple", {"A": "g", "C": "b", "G": "k", "T": "r"}
    )

    # Get signals
    peaks = seq.annotations["peak positions"]
    trace_x = seq.annotations["trace_x"]
    traces_y = [seq.annotations["channel " + str(i)] for i in range(1, 5)]
    bases = seq.annotations["channels"]

    xlim_left, xlim_right = peaks[region_start] - 1, peaks[region_end] + 0.5

    # subset peak and sequence
    # TODO: this might fix the bug
    peak_start = peaks[0]
    peak_zip = [
        (p, s)
        for i, (p, s) in enumerate(zip(peaks, seq))
        if region_start <= i <= region_end
    ]
    peaks, seq = list(zip(*peak_zip))

    # subset trace_x and traces_y together
    trace_zip = [
        (x + peak_start, *ys)
        for x, *ys in zip(trace_x, *traces_y)
        if xlim_left <= x <= xlim_right
    ]
    if not trace_zip:
        return ax
    trace_x, *traces_y = list(zip(*trace_zip))

    # Plot traces
    trmax = max(map(max, traces_y))
    for base in bases:
        trace_y = [1.0 * ci / trmax for ci in traces_y[bases.index(base)]]
        ax.plot(trace_x, trace_y, color=_colors[base], lw=2, label=base)
        ax.fill_between(
            trace_x, 0, trace_y, facecolor=_colors[base], alpha=0.125
        )

    # Plot bases at peak positions
    for i, peak in enumerate(peaks):
        #  LOGGER.debug(f"{i}, {peak}, {seq[i]}, {xlim_left + i}")
        ax.text(
            peak,
            -0.11,
            seq[i],
            color=_colors[seq[i]],
            va="center",
            ha="center",
            alpha=0.66,
            fontsize="x-large",
            fontweight="bold",
        )

    ax.set_ylim(bottom=-0.15, top=1.05)
    #  peaks[0] - max(2, 0.02 * (peaks[-1] - peaks[0])),
    #  right=peaks[-1] + max(2, 0.02 * (peaks[-1] - peaks[0])),
    ax.set_xlim(xlim_left + 0.5, xlim_right)
    ax.set_xticks(peaks)
    ax.set_xticklabels(list(range(region_start + 1, region_end + 2)))
    # hide y axis
    ax.set_yticklabels([])
    ax.get_yaxis().set_visible(False)
    # hide border
    ax.spines["left"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["top"].set_visible(False)
    # hide grid
    ax.grid(False)
    # set legend
    ax.legend(loc="upper left", bbox_to_anchor=(0.95, 0.99))
    return ax
Exemplo n.º 28
0
    def makeHDPlot(self, spk_times: np.array = None,
                   ax: matplotlib.axes = None, **kwargs) -> matplotlib.axes:
        self.initialise()
        spk_times_in_pos_samples = self.getSpikePosIndices(spk_times)
        spk_weights = np.bincount(
            spk_times_in_pos_samples, minlength=self.npos)
        rmap = self.RateMapMaker.getMap(spk_weights, 'dir')
        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='polar')
        # need to deal with the case where the axis is supplied but
        # is not polar. deal with polar first
        theta = np.deg2rad(rmap[1][0])
        ax.clear()
        r = rmap[0]
        r = np.insert(r, -1, r[0])
        if 'polar' in ax.name:
            ax.plot(theta, r)
            if 'fill' in kwargs:
                ax.fill(theta, r, alpha=0.5)
            ax.set_aspect('equal')
        else:
            pass

        # See if we should add the mean resultant vector (mrv)
        if 'add_mrv' in kwargs:
            from ephysiopy.common.statscalcs import mean_resultant_vector
            angles = self.dir[spk_times_in_pos_samples]
            r, th = mean_resultant_vector(np.deg2rad(angles))
            ax.plot([th, th], [0, r*np.max(rmap[0])], 'r')
        if 'polar' in ax.name:
            ax.set_thetagrids([0, 90, 180, 270])
        return ax
Exemplo n.º 29
0
def plot_openness_by_hour(data: list, period: dict, ax: Axes):
    """
    Plots the openness by hour from the raw data.

    :param data: Raw data
    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    num_hrs = 24

    # Get data
    hour_bins = get_openness_by_hour(data, period)

    # Plot bar chart
    ax.bar(range(num_hrs + 1), hour_bins)

    # Decorate the axes
    ax.yaxis.grid(True, which="both", linestyle="-.")
    ax.set_xlim(1, num_hrs)
    ax.set_xticks(range(num_hrs + 1))
    ax.set_xticklabels([f"{t:02d}" for t in ax.get_xticks()])
    ax.set_yticklabels([f"{o * 100:.1f}{percent()}" for o in ax.get_yticks()])
    ax.set_ylabel("Andel åpen")
    ax.set_xlabel("Tid på døgnet")
Exemplo n.º 30
0
def plot_histogram(data: List[np.float64], bins: int, axes: matplotlib.axes):
    axes.hist(x=data, bins=bins)
    axes.set_title('KDE plot')
    axes.set_xlabel('x')
    axes.set_ylabel('f')