def MTSALLoss(y_pred, y_true): assert isinstance(y_pred, torch.Tensor) assert isinstance(y_true, torch.Tensor) loss1 = torch.nn.MSELoss()(y_pred, y_true) y_pred1, y_true1 = cmap(fd, [y_pred, y_true]) loss2 = torch.nn.MSELoss()(y_pred1, y_true1) y_pred2, y_true2 = cmap(fd, [y_pred1, y_true1]) loss3 = torch.nn.MSELoss()(y_pred2, y_true2) return loss1 + 4.5 * loss2 + 10 * loss3
def __getitem__(self,idx): if idx>=self.len: raise StopIteration name=self.filenames[idx] get_path=lambda x:join(self.home_dir,x,name) names=cmap(get_path,['s1','mix','aux']) wavs=cmap(self.load,names) specs=cmap(self.fft,wavs) s1,mix,aux=specs angle=np.cos(np.angle(mix)-np.angle(s1)) s1,mix,aux=cmap(np.abs,[s1,mix,aux]) return torch.Tensor(mix).cuda(),torch.Tensor(aux).cuda(),torch.Tensor(s1*angle).cuda()
from utils import cmap, compose, invoker, unpack, at, reduceUntil from functools import partial, reduce from itertools import permutations, chain from aoc.intcode import Runner parse = compose(list, cmap(int), invoker('split', ',')) # runs Intcode several times by piping their input/output with [phase[index], previousOutput] def runSequence(sequence, intcode, endCondition, startSignal=0): runners = [Runner(iter([phase])) for phase in sequence] runnerIterators = [runner.output_iterator(intcode) for runner in runners] # pipe last signal to current runner's input and add its next output signal to signals def step(signals, index): runners[index].feed(signals[-1]) signal = next(runnerIterators[index], None) return signals + [signal], (index + 1) % len(runners) return reduceUntil(endCondition, unpack(step), ([startSignal], 0))[0] oneLoop = unpack(lambda outputs, index: index == 0 and len(outputs) > 1) noMoreValues = unpack(lambda outputs, index: outputs[-1] is None) # -1 to get last in part A; -2 to get last in part B, since B stops on last = None (no more values) one = compose( max, cmap(at(-1)), lambda intcode: [ runSequence(sequence, intcode, oneLoop) for sequence in permutations(range(0, 5)) ], parse) two = compose(
# returns the positions at which the factor at pattern_index appears in the sequence # that repeats each value in PATTERN repeat_size times def positions(pattern_index, repeat_size): position = pattern_index * repeat_size position -= 1 # offset for i in count(): base = len(PATTERN) * repeat_size * i yield from range(base + position, base + position + repeat_size) digitize = lambda n: abs(n) % 10 # we can see the second half of the sequence is just accumulating up the second half of the digits, starting from the end phase_second_half = compose(list, reversed, list, cmap(digitize), accumulate, reversed) # calculate phase by doing the regular computation for the first half, and the "optimized" computation for the second def phase_full(sequence): length = len(sequence) value_at = lambda index: sum(sequence[ j] * factor for factor in [-1, 1] for j in takewhile( lambda j: j < length, positions(PATTERN.index(factor), index + 1))) first_half = [digitize(value_at(index)) for index in range(0, length // 2)] second_half = phase_second_half(sequence[length // 2:]) return first_half + second_half toSequence = compose(list, cmap(int), list, str)
from utils import cmap, compose, operation, reduceUntil, unpack from text import toLines from functools import partial parse = compose(cmap(int), toLines) fuel = compose(operation('sub', 2), operation('floordiv', 3)) realFuel = lambda mass: reduceUntil( unpack(lambda carry, mass: fuel(mass) <= 0), unpack(lambda carry, mass: (carry + fuel(mass), fuel(mass))), (0, mass))[0] one = compose(sum, cmap(fuel), parse) two = compose(sum, cmap(realFuel), parse)
from utils import cmap, compose, invoker, flatten from functools import partial from space import Point from aoc.intcode import Runner from itertools import count parse = compose(list, cmap(int), invoker('split', ',')) def run(code, intcode): runner = Runner(Runner.ASCII_input(code)) runner.run(intcode) return runner.output def output(line): # print result (hull damage) if found, otherwise interpret the full output as a debug message return line[-1] if line[-1] > 1000 else ''.join(chr(c) for c in line) LINES_ONE = [ 'OR D J', # tell the droid to jump if his landing position is not a hole 'OR A T', 'AND B T', 'AND C T', 'NOT T T', 'AND T J' # tell the droid NOT to jump if ALL the positions prior to landing are ground ] # same as part 1, but check that after a jump we're not stuck LINES_TWO = LINES_ONE + [
from utils import cmap, compose, invoker, unpack, chunks from functools import partial import re N = 25 M = 6 L = N * M BLACK = '0' WHITE = '1' TRANSPARENT = '2' parse = partial(chunks, L) isOpaque = lambda value: value != TRANSPARENT showImage = lambda layer: '\n'.join(row for row in (''.join(layer[i:i + N]) for i in range(0, L, N))) # sub 0s for whitespaces and add a space between columns for readability makeReadable = compose(partial(re.sub, r'0', ' '), partial(re.sub, r'(0|1)', r'\g<1> ')) one = compose(lambda layer: layer.count('1') * layer.count('2'), partial(min, key=invoker('count', '0')), parse) two = compose(makeReadable, showImage, list, cmap(compose(next, partial(filter, isOpaque))), unpack(zip), parse)
from utils import cmap, compose, invoker, at, unpack, dictBuilder, switch, identity from text import patternGroups, toLines from functools import partial from itertools import product, permutations from space import Point import re CENTER = Point((0, 0)) # split input into lines, and each line (a wire) into a series of steps: [{'direction': 'U', 'length': 23}, {'direction' ....}] formatStep = compose(dictBuilder({'direction': str, 'length': int}), partial(patternGroups, r'([URDL])(\d+)')) formatWire = compose(cmap(formatStep), invoker('split', ',')) parseAll = compose(cmap(formatWire), toLines) # transforms a wire (a list of steps) into a list of segments def trace(wire): edges = [CENTER] for stretch in wire: edges.append(travel(stretch, edges[-1])) return list(zip(edges[:-1], edges[1:])) # given a wire stretch (e.g. U41) and a starting Point, returns the destination point def travel(stretch, origin): vector = switch(lambda direction, length: direction, { 'U': lambda direction, length: Point((0, length)), 'R': lambda direction, length: Point((length, 0)), 'D': lambda direction, length: Point((0, -length)), 'L': lambda direction, length: Point((-length, 0)), }) return Point(origin) + vector(**stretch)
from utils import cmap, compose, invoker, identity from text import toLines from functools import partial from collections import defaultdict ROOT = 'COM' parse = compose(list, cmap(invoker('split', ')')), toLines) def buildOrbits(pairs): orbits = defaultdict(list) for static, orbiter in pairs: orbits[static].append(orbiter) return orbits def countOrbits(source, orbits): def count(source, level=0): return level + sum( [count(orbiter, level + 1) for orbiter in orbits[source]]) return count(source) def path(target, orbits): def trace(current): orbiters = orbits[current[-1]] if len(orbiters) == 0: return current if current[-1] == target else None paths = (trace(current + [orbiter]) for orbiter in orbiters)
from functools import partial from collections import defaultdict from itertools import islice, cycle from math import inf as infinity from space import Point class Asteroid: def __init__(self, coords): self.coords = coords self.traces = defaultdict(list) ASTEROID = '#' buildAsteroids = lambda grid: [Asteroid((j, i)) for i, row in enumerate(grid) for j, column in enumerate(row) if row[j] == ASTEROID] parse = compose(buildAsteroids, cmap(list), toLines) # for each asteroid, trace lines to the rest. Such traces are grouped by line/direction; where the line is defined by its slope (k in y=k*x) and # direction dictates the direction (<=> the other asteroid is to the right of the one we trace from) def trace(asteroids): for i in range(len(asteroids)): asteroid = asteroids[i] for j in range(i + 1, len(asteroids)): other = asteroids[j] x, y = (a - b for a, b in zip(asteroid.coords, other.coords)) slope = (y / x) if x != 0 else infinity positive = other.coords > asteroid.coords asteroid.traces[(slope, positive)].append(other) other.traces[(slope, not positive)].append(asteroid) # sort by distance
from utils import compose, cmap, attr, alter, isolate, iterate from text import toLines from space import Point from functools import partial, reduce from itertools import islice import re import math class Body: def __init__(self, coords): self.position = Point(tuple(coords)) self.velocity = Point(tuple([0] * self.position.dimension)) parseBody = compose(Body, cmap(int), partial(re.findall, r'-?\d+')) parse = compose(list, cmap(parseBody), toLines) sign = lambda n: n // max(1, abs(n)) gravitate = lambda body, towards, velocity: velocity + Point( tuple(sign(b - a) for a, b in zip(body.position, towards.position))) adjust = lambda system: [ alter('velocity', compose(*[partial(gravitate, body, other) for other in rest]))(body) for body, rest in isolate(system) ] move = lambda system: [ alter('position', lambda position: position + body.velocity)(body) for body in system ]
from utils import cmap, compose from text import toLines from functools import partial, reduce def parse_move(line): if line == 'deal into new stack': return {'move': 'reverse', 'args': []} if line[0:3] == 'cut': return {'move': 'cut', 'args': [int(line[4:])]} if line[0:19] == 'deal with increment': return {'move': 'offset', 'args': [int(line[20:])]} parse = compose(list, cmap(parse_move), toLines) offset = lambda value, index, deck_size: (index * value) % deck_size cut = lambda value, index, deck_size: (index - value) % deck_size reverse = lambda index, deck_size: deck_size - index - 1 # given an index i, 0 <= i < deck_size, returns the position of the index pointing to the same # card of the deck after it has been shuffled apply_move = lambda index, deck_size, move, args: globals()[move](*args, index, deck_size) shuffle_index = lambda index, deck_size, shuffle: reduce( lambda index, move: apply_move(index, deck_size, move['move'], move['args'] ), shuffle, index) # not my solution def find(times, final_position, deck_size, moves):
from utils import cmap, compose, invoker, flatten from functools import partial from space import Point from aoc.intcode import Runner from itertools import count parse = compose(list, cmap(int), invoker('split', ',')) SCAFFOLD = '#' VOID = '.' directions = { Point((0, 1)): 'v', Point((-1, 0)): '<', Point((0, -1)): '^', Point((1, 0)): '>', } def draw(intcode): runner = Runner() runner.run(intcode) return runner.output # drawing (string) to grid (dict) drawing_to_dict = lambda drawing: {(i, j): char for j, line in enumerate(drawing.split( '\n')) for i, char in enumerate(line)} walkable = lambda coords, grid: coords in grid and grid[coords] != VOID find_intersections = lambda grid: (coords for coords in grid if walkable(