Ejemplo n.º 1
0
 def __init__(self, robot_move_strategy, topics):
     # type: (ExploreMoveStrategy, List[dict]) -> None
     self.robot_move_strategy = robot_move_strategy
     self.topic_identifiers = lmap(lambda topic: topic['identifier'],
                                   topics)
     self.topics_values = lmap(lambda topic: topic['explore'], topics)
     self.continue_enabled = all(
         map(lambda topic: topic['explore'].get('continue', False), topics))
     self.publishers_types = lmap(
         lambda topic: dynamic_import(topic['type']), topics)
     self.publishers = lmap(
         lambda topic: rospy.Publisher(topic[1]['identifier'],
                                       self.publishers_types[topic[0]],
                                       queue_size=1), enumerate(topics))
     self.responders = lmap(lambda topic: self.get_responder(topic), topics)
Ejemplo n.º 2
0
def p1(inp):
    grid = np.array(lmap(list, inp.strip().splitlines()))
    pos = np.array(np.where(grid == "@"))[:, 0]
    grid[tuple(pos)] = "."
    allkeys = set(list(re.sub(r"[^a-z]", "", inp)))
    # print(allkeys)

    # if DISPLAY:
    #     import pygame as pg

    #     pg.init()
    #     screen = pg.display.set_mode((grid.shape[0] * SCALE, grid.shape[1] * SCALE))
    #     gridsurf = pg.surface.Surface(grid.shape)

    # def display():
    #     for ev in pg.event.get():
    #         if ev.type == pg.QUIT:
    #             sys.exit(0)
    #     pg.surfarray.blit_array(gridsurf, grid)
    #     pg.draw.circle(gridsurf, POS, tuple(pos), 0)
    #     pg.transform.scale(
    #         gridsurf, (grid.shape[0] * SCALE, grid.shape[1] * SCALE), screen
    #     )
    #     pg.display.flip()

    return dijkstra(grid, allkeys, tuple(pos))
Ejemplo n.º 3
0
def parse(s):
    def parseIng(x):
        q, c = x.split(" ")
        return (int(q), c)

    ret = [lmap(lambda x: parseIng(x.strip()), re.split(r"=>|,", l)) for l in s.splitlines()]
    return [(l[:-1], l[-1]) for l in ret]
Ejemplo n.º 4
0
def main():
    inp = data_lines_nums()
    # inp = [[-1, 0, 2], [2, -10, -7], [4, -8, 8], [3, 5, -1]]
    # inp = [[-8, -10, 0], [5, 5, 10], [2, -7, 3], [9, -8, -3]]
    inp = lmap(list, zip(inp, [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]))
    inp = np.array(inp)

    print(f"Solution for part 1:\n{p1(inp)}")
    print(f"Solution for part 2:\n{p2(inp)}")
Ejemplo n.º 5
0
Archivo: Day17.py Proyecto: vypxl/aoc
def p1(inp, debug=False):
    scaffolds = ''.join(
        map(chr,
            IntComputer(inp, name="ASCII", debug=debug).run()))
    scaffolds = np.array(lmap(list, scaffolds.strip().splitlines()))

    psum = 0
    for x in range(1, scaffolds.shape[0] - 1):
        for y in range(1, scaffolds.shape[1] - 1):
            if scaffolds[x, y] == '#' and scaffolds[
                    x + 1,
                    y] == '#' and scaffolds[x, y + 1] == '#' and scaffolds[
                        x - 1, y] == '#' and scaffolds[x, y - 1] == '#':
                psum += x * y
    return psum
Ejemplo n.º 6
0
    def find_new_path(self):
        rospy.loginfo("Finding new path")
        if not self.actions:
            self.current_path = [self.state]
            return

        backtrace = []

        new_states = lmap(
            lambda actions: tuple(
                action.to_state(self.state) for action in actions),
            self.actions)
        combined_possible_states = self.get_combined_possible_new_states(
            new_states)
        for new_state in combined_possible_states:
            if new_state in self.inaccessible or new_state in self.visited:
                continue
            reward = self.get_reward(new_state)
            backtrace.append((reward, new_state, tuple(self.state)))
        backtrace.sort(key=lambda pair: pair[0])
        self.backtrace += lmap(lambda pair: pair[1:], backtrace)
        next_state, source = self.backtrace.pop() if self.backtrace else tuple(
            [None, None])
        self.find_path(source, next_state)
Ejemplo n.º 7
0
    def move(self, *additional_steps):
        steps = self.get_steps(additional_steps)

        while True:
            states = self.robot_move_strategy.get_next_states()

            if not states:
                self.log_for_each_topic('is unable to get to next state')
                break

            responses = lmap(lambda args: self.move_to_state(*args),
                             enumerate(states))

            self.robot_move_strategy.give_feedback(responses)
            self.log_for_each_topic(' goal reached?: ', responses)

            for step in steps:
                threading.Thread(target=step).start()
Ejemplo n.º 8
0
    def __init__(self, **kwargs):
        self.state_machine = kwargs['state_machine']
        self.model_confs = kwargs['model_confs']
        if not self.state_machine:
            rospy.logerr("stateMachine not specified in config")
            raise RuntimeError("stateMachine not specified in config")
        self.state_values = {
            int(key): self.state_machine['values'][key]
            for key in self.state_machine['values']
        }
        self.edges = {
            int(key): lmap(int, self.state_machine['edges'][key])
            for key in self.state_machine['edges']
        }
        self.edge_labels = {
            eval(key): self.state_machine['labels'][key]
            for key in self.state_machine['labels']
        }
        self.timestamps = {
            eval(key): self.state_machine['timestamps'][key]
            for key in self.state_machine['timestamps']
        }
        self.initial_state = int(self.state_machine['initialState'])

        self.state_machine['values'] = self.state_values
        self.state_machine['edges'] = self.edges
        self.state_machine['labels'] = self.edge_labels
        self.state_machine['timestamps'] = self.timestamps

        self.topics = []
        self.actions = []
        self.action_lens = []
        self.visited = set()
        self.inaccessible = defaultdict(set)
        self.path = []
        self.path_cursor = 0
        self.prev_state = None
        self.state = None
        self.next_state = None
        self.connecting = False
        self.success = True
        self.closest_pairs = None
        self.going_back = False
        self.timestamp = None
Ejemplo n.º 9
0
Archivo: intcode.py Proyecto: vypxl/aoc
    async def async_run(self):
        """Start executing instructions until a hlt instruction and return self.out"""
        self.out = []
        self.input = self.data.copy()
        self.mem.fill(0)
        self.mem[: self.program.size] = self.program
        self.ip = 0
        self.rel = 0

        while 1:
            op = self.mem[self.ip]
            modes = lmap(lambda i: op // i % 10, [100, 1000, 10000])
            op = op % 100
            _, nparams = self.OPCODES[op]
            params = list(zip(self.mem[self.ip + 1 : self.ip + 1 + nparams], modes))

            self.ip = await self.__operate(op, *params)
            if self.ip < 0:
                break

        return self.out
def run(k, args, xs, conn):
    """
    Parameters
    ----------
    k : index of thread
    args : struct of all arguments
    xs: list of ids (int) of data points
    conn : pipe to the main thread

    function is run as a thread
    iterates though all x in xs and samples errors
    and reports them back to the main thread 
    """
    np.random.seed(1000 * args.seed + k)
    data = lmap(itemgetter(0), get_dataset())
    a_min = -args.alpha_min_max
    a_max = args.alpha_min_max
    for i in xs:
        path = data[i]
        y, sr = librosa.load(path, sr=None)
        for _ in range(args.K):
            a = np.random.uniform(a_min, a_max)
            b = np.random.normal(0, args.beta_std)
            diff, spect_diff, l_spect_diff = transform(y, sr, a, b, args)
            l1 = np.linalg.norm(diff, ord=1)
            l2 = np.linalg.norm(diff, ord=2)
            linf = np.linalg.norm(diff, ord=np.inf)
            ret = [i, a, b, l1, l2, linf]
            s_l1 = np.linalg.norm(np.ravel(spect_diff), ord=1)
            s_l2 = np.linalg.norm(np.ravel(spect_diff), ord=2)
            s_linf = np.linalg.norm(np.ravel(spect_diff), ord=np.inf)
            l_s_l1 = np.linalg.norm(np.ravel(l_spect_diff), ord=1)
            l_s_l2 = np.linalg.norm(np.ravel(l_spect_diff), ord=2)
            l_s_linf = np.linalg.norm(np.ravel(l_spect_diff), ord=np.inf)
            ret.extend([s_l1, s_l2, s_linf, l_s_l1, l_s_l2, l_s_linf])
            conn.send(ret)
    parser.add_argument('--beta_std',
                        type=float,
                        default='0.85',
                        help='standard deviation for beta')
    args = parser.parse_args()

    np.random.seed(args.seed)
    random.seed(args.seed)

    data = get_dataset()
    L = len(data)
    N = min(L, args.N)
    I = list(range(L))
    samples = list(random.sample(I, N))

    data = lmap(itemgetter(0), get_dataset())

    a_min = -args.alpha_min_max
    a_max = args.alpha_min_max

    arg_tuples = []

    for i in samples:
        path = data[i]
        y, sr = librosa.load(path, sr=None)
        a_ = [np.random.uniform(a_min, a_max) for _ in range(args.K)]
        betas_ = [
            np.random.normal(0, args.beta_std, 100) for _ in range(args.K)
        ]
        arg_tuples.append((args, y, sr, a_, betas_))
    with mp.Pool() as pool:
Ejemplo n.º 12
0
Archivo: Day17.py Proyecto: vypxl/aoc
def p2(inp, debug=False):
    program = """A,B,A,B,C,B,A,C,B,C
L,12,L,8,R,10,R,10
L,6,L,4,L,12
R,10,L,8,L,4,R,10
n
"""
    # Solved by hand; notes:
    # ................................#####..............
    # ................................#...#..............
    # ................................#...#..............
    # ................................#...#..............
    # ................................#...#..............
    # ................................#...#..............
    # ..........................###########..............
    # ..........................#.....#..................
    # ..........................#.....#..................
    # ..........................#.....#..................
    # ..........................#.....#..................
    # ..........................#.....#..................
    # ......................###########..................
    # ......................#...#........................
    # ......................#...#........................
    # ......................#...#........................
    # ......................#...#########................
    # ......................#...........#................
    # ..........#...........#...........#................
    # ..........#...........#...........#................
    # ..........#...........#####.......#................
    # ..........#...............#.......#................
    # ..........#...............#.......#................
    # ..........#...............#.......#................
    # ..........#...........#######.....#................
    # ..........#...........#...#.#.....#................
    # ..........#.........#############.#...#############
    # ..........#.........#.#...#.#...#.#...#............
    # ..........#####.....#.#############...#............
    # ..............#.....#.....#.#...#.....#............
    # ..............#.....#.....#######.....#............
    # ..............#.....#.......#.........#............
    # ..............#.....#.......#.........#............
    # ..............#.....#.......#.........#............
    # ..............#.....#.......###########............
    # ..............#.....#..............................
    # ....###########.....#..............................
    # ....#...............#..............................
    # ....#.....#########.#########......................
    # ....#.....#.......#.........#......................
    # ....#.....#.......#.........#......................
    # ....#.....#.......#.........#......................
    # ###########.......#.........#......................
    # #...#.............#.........#......................
    # #...#.............#.........#......................
    # #...#.............#.........#......................
    # #...#.............#.........#......................
    # #...#.............#.........#......................
    # #####.............###########......................
    # L,12,L,8,R,10,R,10,L,6,L,4,L,12,L,12,L,8,R,10,R,10,L,6,L,4,L,12,R,10,L,8,L,4,R,10,L,6,L,4,L,12,L,12,L,8,R,10,R,10,R,10,L,8,L,4,R,10,L6,L4,L12,R,10,L,8,L,4,R,10
    # LFFFFFFFFFFFFLFFFFFFFFRFFFFFFFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF LFFFFFFFFFFFFLFFFFFFFFRFFFFFFFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF RFFFFFFFFFFLFFFFFFFFLFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF LFFFFFFFFFFFFLFFFFFFFFRFFFFFFFFFFRFFFFFFFFFF RFFFFFFFFFFLFFFFFFFFLFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF RFFFFFFFFFFLFFFFFFFFLFFFFRFFFFFFFFFF
    # L,12,L,8,R,10,R,10
    # L,6,L,4,L,12
    # R,10,L,8,L,4,R,10
    # ABABCBACBC

    ret = -1

    def write(val):
        nonlocal ret
        if val < 128:
            sys.stdout.write(chr(val))
        else:
            ret = val

    IntComputer("2" + inp[1:],
                name="ASCII",
                inp=lmap(ord, program),
                writef=write,
                debug=debug).run()
    return ret
Ejemplo n.º 13
0
def main():
    inp = lmap(int, data().strip())
    inp = np.array(inp, dtype=np.int8)

    print(f"Solution for part 1:\n{p1(inp)}")
    print(f"Solution for part 2:\n{p2(inp)}")