Ejemplo n.º 1
0
def main():
    grid = parse(sys.stdin.readlines())

    after100 = nth(iterate(animate, grid), 100)
    print('part1: ', count_on(after100))

    after100 = nth(iterate(pipe(animate, turn_edges), grid), 100)
    print('part1: ', count_on(after100))
Ejemplo n.º 2
0
def main():
  grid = parse(sys.stdin.readlines())

  after100 = nth(iterate(animate, grid), 100)
  print('part1: ', count_on(after100))

  after100 = nth(iterate(pipe(animate, turn_edges), grid), 100)
  print('part1: ', count_on(after100))
Ejemplo n.º 3
0
def metoda(matrix):
    error=1
    pa=[utils.a(matrix,1)]
    while error >0.000001:
    # for i in range(1000):
        utils.iterate(matrix)
        pa.append(utils.a(matrix,1))
        error=abs(pa[-1]-pa[-2])
        stdout.write("\r{0:0.20f}    ".format(error))
        stdout.flush()
    print(" ")
    return pa
Ejemplo n.º 4
0
def solve_by_reduction(p):
    """ 
       Yields (p_0, None), (p_1, alpha_0), (p_2, alpha_1) ...
       where p_0 = p, alpha_0 = None
             alpha_i = a Newton-Raphson root of p_i
             p_{i+1} = p_i // - alpha_i
             
    """
    def solve_divide(state):
        (p, _) = state
        alpha = p.solve()
        return (p // -alpha, alpha)

    yield from ut.iterate(solve_divide, (p, None))
def entropy_drift_analysis(sigma=2, color='b', color_p='g'):
    """why is convergence so difficult to obtain for, say, sigma = 2?  Explore selection/mutation balance."""
    n = 16
    L = 16
    matrix = sample_matrix(L, sigma)
    ringer = ringer_motif(matrix, n)
    mutants = [
        iterate(mutate_motif, ringer, i) for i in trange(256)
        for j in range(10)
    ]
    dists = [
        motif_hamming_distance(ringer, mutant) for mutant in tqdm(mutants)
    ]
    fs = [log_fitness(matrix, mutant, G) for mutant in tqdm(mutants)]
    fps = []
    trials = 100
    for mutant in tqdm(mutants):
        nexts = []
        f = log_fitness(matrix, mutant, G)
        for i in range(trials):
            mutant_p = mutate_motif(mutant)
            fp = log_fitness(matrix, mutant_p, G)
            if log(random.random()) < fp - f:
                nexts.append(fp)
            else:
                nexts.append(f)
        fps.append(mean(nexts))
    plt.subplot(3, 1, 1)
    plt.scatter(dists, fs, color=color, marker='.')
    plt.scatter(dists, fps, color=color_p, marker='.')
    #plt.semilogy()
    plt.subplot(3, 1, 2)
    plt.scatter(dists, [(f - fp) / f for (f, fp) in zip(fs, fps)],
                color=color,
                marker='.')
    plt.plot([0, len(fs)], [0, 0], linestyle='--', color='black')
    plt.subplot(3, 1, 3)
    diffs = [fp - f for f, fp in zip(fs, fps)]
    plt.scatter(fs, diffs, marker='.', color=color)
    interpolant = poly1d(polyfit(fs, diffs, 1))
    plt.plot(*pl(interpolant, [min(fs), max(fs)]))
    plt.plot([min(fs), max(fs)], [0, 0], linestyle='--', color='black')
    minx, maxx = min(fs + fs), max(fs + fps)
Ejemplo n.º 6
0
def first_repeat(system):
    dimension = system[0].position.dimension
    # serializer of one axis for comparison between system states
    serialize_axis = lambda system, axis: [
        body.position[axis] for body in system
    ] + [body.velocity[axis] for body in system]
    # we assume the initial state belongs to the repeating cycle and is thus the first state to be eventually repeated
    initial = tuple(serialize_axis(system, axis) for axis in range(dimension))
    # store the cycle length for each axis
    cycle_lengths = [0] * dimension
    counted_moving_system = enumerate(iterate(step, system))
    while not all(cycle_lengths):
        count, current = next(counted_moving_system)
        for axis in range(dimension):
            if cycle_lengths[axis] == 0 and serialize_axis(
                    current, axis) == initial[axis]:
                cycle_lengths[axis] = count

    least_common_multiple = lambda a, b: a * b // math.gcd(a, b)
    return reduce(least_common_multiple, cycle_lengths)
def convergence_wall_exploration(sigma=3,
                                 mutations=range(0, 100, 10),
                                 iterations=10000,
                                 Ne=5,
                                 p=None,
                                 function=sella_hirsch_imh):
    n = 16
    L = 16
    if p is None:
        p = 1.0 / (n * L)
    matrix = sample_matrix(L, sigma)
    ringer = ringer_motif(matrix, n)
    mutants = [iterate(mutate_motif, ringer, i) for i in mutations]
    matrix_chains = [
        function(Ne=Ne, matrix=matrix, init=mutant, iterations=iterations, p=p)
        for mutant in tqdm(mutants)
    ]
    for matrix_chain in matrix_chains:
        plot_matrix_chain_log_fitness(matrix_chain)
    stats = [
        map(lambda m: log_fitness(matrix, m, G), chain)
        for (matrix, chain) in tqdm(matrix_chains)
    ]
    return stats
Ejemplo n.º 8
0
# perform HTTP GET request to get the HTML content from the blog
html = utils.http.get('https://arinerron.com/blog/')

# So here's an example snippet of the contents of `html`:
#   <div id="post">
#     <div id="name"><a href="/blog/posts/2">The Title of the Blog Post</a></div>
#     <div id="date" style="user-select: none;">November 33, 2070</div><br>
#     <div id="snippet">The description is here.</div>
#   </div>
# As you can see, the name is stored inside of the div with the id "name".
# The id "name" id is defined for each blog post, so let's iterate each
# instance of it to get the name of each post

# loop code for each case of the string '<div id="name">'
for case in utils.iterate(html, '<div id="name">', skip_first=True):
    # At this point, the variable `case` will contain something similar to
    # the following for each instance of the delimiter:
    #   <a href="/blog/posts/2">The Title of the Blog Post</a></div>
    # As you can see, the blog post title is wrapped in an <a> element.
    # The problem is that the blog post URL (/blog/posts/X) appears to
    # change for each post. However, the string '">' is always preceding the
    # blog post title, therefore, all we need to do is get the string after
    # the string '">'.

    # redefine case: set it to the string after first instance of the delimiter '">'
    case = utils.after(case, '">', first=True)

    # Okay. Now, the variable `case` will contain something similar to this:
    #   The Title of the Blog Post</a></div>
    # That's great. Now we just need to remove the last part of the string
Ejemplo n.º 9
0
def generate_passwords(start):
    return iterate(next_password, start)
Ejemplo n.º 10
0
def code(row, col):
    return nth(iterate(next_code, 20151125), ns(row, col))
Ejemplo n.º 11
0
def main():
  n = sys.stdin.readline().strip()

  part1 = nth(iterate(las, n), 40)
  print "part 1: ", len(part1)
  print "part 2: ", len(nth(iterate(las, part1), 10))
Ejemplo n.º 12
0
    out_file = open(out_file_path,
                    mode='wb+') if out_file_path else sys.stdout.buffer

    data = pickle.load(in_file)

    matrix = data.get('matrix')
    method_generator = methods[method_name]

    W, H = ut.initialize_random(*matrix.shape, decomposition_rank)

    start = time.time()

    result, errors_trace = ut.iterate(
        method_generator,
        matrix,
        W,
        H,
        precision=precision,
        method_name=method_name,
    )

    W, H = result
    elapsed = time.time() - start

    print(errors_trace[-1], end='')

    pickle.dump(
        {
            'method_name': method_name,
            'precision': precision,
            'decomposition_rank': decomposition_rank,
            'errors_trace': errors_trace,
Ejemplo n.º 13
0
def code(row, col):
  return nth(iterate(next_code, 20151125), ns(row, col))
Ejemplo n.º 14
0
def main():
    n = sys.stdin.readline().strip()

    part1 = nth(iterate(las, n), 40)
    print "part 1: ", len(part1)
    print "part 2: ", len(nth(iterate(las, part1), 10))
Ejemplo n.º 15
0
    for other, amount in formulae[chemical]['requirements']:
        factor = quantity / total if fractionable else math.ceil(quantity /
                                                                 total)
        materials[other] += amount * factor
    materials[chemical] = 0
    return materials


# no more chemical reactions needed if we only have ORE
finished = lambda state: all(amount == 0 or chemical == 'ORE'
                             for chemical, amount in state.items())

# finds needed ORE to get the specified materials with the specified formulae
# fractionable=False -> minimum ORE; fractionable=True -> exact ORE (asymptotically)
calculate_ore = lambda materials, fractionable, formulae: next(
    materials['ORE'] for materials in iterate(
        partial(react, formulae, fractionable=fractionable), materials)
    if finished(materials))


# finds how much FUEL we can get with 'available' amount of ORE, then
# find exact ore/fuel ratio, then check how much we can make with it, then
# check and adjust off-by-1 error
def find_fuel(available, formulae):
    ratio = calculate_ore(defaultdict(int, {'FUEL': 1}), True, formulae)
    fuel = math.floor(available / ratio)
    if calculate_ore(defaultdict(int, {'FUEL': fuel}), False,
                     formulae) > available:
        fuel -= 1
    return fuel

Ejemplo n.º 16
0
def generate_passwords(start):
  return iterate(next_password, start)
Ejemplo n.º 17
0
    def approximations():  # yields approximations one by one
        def improve_root(state):
            (r, _) = state
            return (r - poly_eval(poly, r) / poly_eval(pdx, r), r)

        yield from ut.iterate(improve_root, (r0, None))