Esempio n. 1
0
def part_2(path: Path) -> int:
    """
    Find how many times a sum of 3 increases
    """
    three_sliding_window = (
        sum(window) for window in sliding_window(read_file_as_ints(path), 3))
    return count_sliding_window_increase(three_sliding_window)
Esempio n. 2
0
 def test_basic(self):
     for iterable, n, expected in [
         ([], 0, [()]),
         ([], 1, []),
         ([0], 1, [(0,)]),
         ([0, 1], 1, [(0,), (1,)]),
         ([0, 1, 2], 2, [(0, 1), (1, 2)]),
         ([0, 1, 2], 3, [(0, 1, 2)]),
         ([0, 1, 2], 4, []),
         ([0, 1, 2, 3], 4, [(0, 1, 2, 3)]),
         ([0, 1, 2, 3, 4], 4, [(0, 1, 2, 3), (1, 2, 3, 4)]),
     ]:
         with self.subTest(expected=expected):
             actual = list(mi.sliding_window(iterable, n))
             self.assertEqual(actual, expected)
Esempio n. 3
0
def run2(path: Path, steps: int) -> int:
    target, mappings = parse_input_file(path)

    # NOTE: Everything in a size 2 sliding window is in mapping
    # Also, each new pair created by an insert is also in mapping
    # This means we don't have to keep the whole string, only a count of each pair in the mappings

    # Init the pair count with the input string
    pair_counts = defaultdict(int)
    for first, second in sliding_window(target, 2):
        pair_counts[(first, second)] += 1

    for _ in range(steps):
        new_pair_counts = defaultdict(int)
        # For each pair, break it into the two new pairs
        # Each of them occurs this many more times
        # e.g. if we have NC -> H and NC: 3
        # then in the new string we'll have NH: 3 and HC: 3
        for (first, second), count in pair_counts.items():
            insert_char = mappings[first + second]
            new_pair_counts[(first, insert_char)] += count
            new_pair_counts[(insert_char, second)] += count
        pair_counts = new_pair_counts

    # Count how many times each letter appears in the pairs
    letter_counts = defaultdict(int)
    for (first, second), count in pair_counts.items():
        letter_counts[first] += count
        letter_counts[second] += count

    # We're double counting because of overlaps, so divide
    for letter, count in letter_counts.items():
        # Plus one handles the edges of the string
        letter_counts[letter] = (count + 1) // 2

    counts = sorted(letter_counts.values())
    return counts[-1] - counts[0]
Esempio n. 4
0
def b(depths):
    window_depths = [sum(window) for window in sliding_window(depths, 3)]
    return a(window_depths)
Esempio n. 5
0
def get_speed_direction(st_diagram,
                        good_spatial_line_idx,
                        plot_st=False,
                        plot_hist=False):
    '''
    TODO: Docstring for get_speed_direction.

    Parameters
    ----------
    st_diagram : TODO
    good_spatial_line_idx: TODO

    Returns
    -------
    TODO

    Notes
    -----
    MED69: good_spatial_line_idx=2466
    MED50: good_spatial_line_idx=2057
    '''
    M, N = st_diagram.shape
    st_diagram_10hz = st_diagram[good_spatial_line_idx %
                                 25::25]  # 25fps == 10hz

    # for i, (sl1, sl2) in enumerate(sliding_window(st_diagram_10hz[:20], 2)):
    # c = correlate(sl2, sl1, mode='same')
    # plt.plot(c, c=f'C{i}', alpha=0.3)
    # plt.plot(c.argmax(), c.max(), 's', c=f'C{i}', alpha=0.5)
    # plt.show()

    c = []
    for sl1, sl2 in sliding_window(st_diagram_10hz, 2):
        c.append(correlate(sl2, sl1, mode='same').argmax() - 1500)
    c = np.array(c)

    # idx = np.where(np.abs(c) < np.mean(c)+5*np.std(c))[0]
    c = c / 25
    c = c[np.abs(c) > 2]
    cmode = mode(c)[0][0]
    c = c[np.abs(c) > np.abs(cmode * .7)]
    c = c[np.abs(c) < np.abs(cmode * 1.3)]
    v = 1 / np.mean(c)

    if plot_st:
        cmap = truncate_colormap('twilight_shifted', 0.1, 0.90)

        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 8))

        extent = (0, N, 0, M)
        img = ax1.imshow(st_diagram,
                         origin='lower',
                         clim=(-7.5, 10),
                         extent=extent,
                         aspect=N / M,
                         cmap=cmap)
        # fig.colorbar(img)

        axins = ax1.inset_axes([0.3, 0.5, 0.68, 0.55])
        axins.imshow(st_diagram,
                     extent=extent,
                     origin="lower",
                     clim=(-7.5, 10),
                     cmap=cmap,
                     aspect=N / M)

        x1, x2, y1, y2 = 1700, 2350, 2300, 2700
        axins.set_xlim(x1, x2)
        axins.set_ylim(y1, y2)
        axins.set_xticks([])
        axins.set_yticks([])
        tag_ax(axins, 'Zoom', pos=(0.05, 0.9), box_color=cmap(0.5))

        for fl in np.arange((1348 - 750 * v) % 250, M, 250):

            def f(x):
                return v * x + fl

            x = np.arange(st_diagram.shape[1])
            ax1.plot(x, f(x), ':', c='0.2', lw=3)
            axins.plot(x, f(x), ':', c='0.2', lw=3)
        ax1.plot(x,
                 f(x),
                 ':',
                 c='0.2',
                 lw=3,
                 label='Trayectoria de los trenes')

        ax1.set_xlabel('Ángulo [rad]', fontsize=18, labelpad=-10)
        ax1.set_ylabel('Tiempo [s]', fontsize=18, labelpad=-14)
        ax1.set_xticks([750, N])
        ax1.set_xticklabels(['$0$', '$2\pi$'], fontsize=16)
        ax1.set_yticks([750, M])
        ax1.set_yticklabels(['$0$', '$12$'], fontsize=16)

        ax1.set_xlim(750, N)
        ax1.set_ylim(750, M)

        ax1.legend(fontsize=16, fancybox=False, loc=4)

        ax2.hist(c * 2 * np.pi / N / (12 / M),
                 bins=9,
                 ec=WHITE_NORD,
                 color=DARK_GRAY_NORD)
        ax2.set_xlabel('Velocidad [rad/s]', fontsize=18)
        ax2.set_ylabel('Frecuencia', fontsize=18)

        plt.savefig(
            f'../../Informes/Labo7_presentacion/figs/velocidad_osc.pdf',
            bbox_inches='tight',
            transparent=True)

        plt.show()

    return v
Esempio n. 6
0
def count_sliding_window_increase(iterator: Iterator[int]):
    """
    Count how many times the iterator increases
    """
    return sum(first < second for first, second in sliding_window(iterator, 2))