Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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")
Ejemplo n.º 4
0
def plot_visit_durations(data: list, ax: Axes):
    """
    Plot the visit durations from the raw data.

    :param data: Raw data
    :param ax: Axes object in which to put the plot
    :return: None
    """
    # Histogram options
    min_visit_s = 30
    max_visit_s = 60 * 60 * 3
    nbins = 150

    # Regression line options
    fit_start = 6
    fit_stop = 144

    # Create histogram
    durations = get_visit_durations(data)
    n, bins, _ = ax.hist(durations, bins=linspace(min_visit_s, max_visit_s, nbins))

    # Create regression line
    bin_width = (bins[fit_stop - 1] - bins[fit_start]) / (fit_start - fit_stop)
    lin_fitting_bins = [b + bin_width / 2 for b in bins[fit_start:fit_stop]]
    lin_fitting_n = n[fit_start:fit_stop]
    [a, b] = polyfit(lin_fitting_bins, log(lin_fitting_n), 1, w=sqrt(lin_fitting_n))
    fitted_n = [exp(b + a * t) for t in lin_fitting_bins]
    regression_line_opts = {"linestyle": "--", "color": "black", "linewidth": 2}
    regression_label_text = "y={:.0f}exp({:.6f}*t)".format(exp(b), a)
    regression_label_coords = (max_visit_s * 0.6, max(n) * 0.5)
    ax.plot(lin_fitting_bins, fitted_n, **regression_line_opts)
    ax.text(*regression_label_coords, regression_label_text)

    # Label axes
    ax.set_xlabel("Varighet for visitt (s)")
    ax.set_ylabel("Andel visitter (vilkårlig)")
    ax.set_yscale("log")
Ejemplo n.º 5
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