예제 #1
0
def gen_trace(kwargs):
    duplicates = lambda U, v: (np.fabs(U - v) < 1e-6).all(axis=0)
    soln = df_sv.fiber_solver(**kwargs)
    fps = df_fx.sanitize_points(soln['Fixed points'], kwargs['f'],
                                kwargs['ef'], kwargs['Df'], duplicates)

    return fps, soln['Fiber trace'].points, soln['Fiber trace'].step_amounts
예제 #2
0
def run_fiber_solver(W, **kwargs):
    """
    rnn-specific convenience wrapper for generic fiber solver and post-processing
    W is the (N,N) weight matrix; kwargs are as in dfibers.solvers.fiber_solver
    """

    # Setup random c for termination criteria
    N = W.shape[0]
    if "c" in kwargs:
        c = kwargs["c"]
    else:
        c = np.random.randn(N,1)
        c = c/np.linalg.norm(c)
        kwargs["c"] = c
    
    if "compute_step_amount" not in kwargs:
        kwargs["compute_step_amount"] = compute_step_amount_factory(W)

    # Run solver from origin
    solution = sv.fiber_solver(
        f = f_factory(W),
        ef = ef_factory(W),
        Df = Df_factory(W),
        v = np.zeros((N,1)),
        terminate = terminate_factory(W, c),
        max_solve_iterations = 2**5,
        **kwargs
    )

    # Post-process fixed points
    fxpts = solution["Fixed points"]
    fxpts = np.concatenate((-fxpts, np.zeros((N,1)), fxpts), axis=1)
    fxpts = fx.sanitize_points(
        fxpts,
        f = f_factory(W),
        ef = ef_factory(W),
        Df = Df_factory(W),
        duplicates = duplicates_factory(W),
    )
    
    # Return post-processed fixed points and full solver result
    return fxpts, solution
예제 #3
0
def run_trials(args):
    basename, proc, N, timeout = args

    # Reseed randomness, start logging, start timing
    np.random.seed()
    logfile = open("%s_p%d_N%d.log" % (basename, proc, N), "w")
    logger = lu.Logger(logfile)
    stop_time = time.clock() + timeout

    # Keep sampling until timeout
    for sample in it.count(0):

        # Sample new network
        f, Df, ef, W, V = rnn.make_known_fixed_points(N)
        dups = rnn.duplicates_factory(W)
        results = {}
        data = {"W": W}

        # Keep fiber-solving until some c finds all V or timeout
        for trial in it.count(0):
            print("proc %d, N %d, sample %d, trial %d" %
                  (proc, N, sample, trial))

            # Run fiber solver
            start_time = time.clock()
            fxpts, solution = rnn.run_fiber_solver(
                W,
                # max_traverse_steps = 2**15,
                stop_time=stop_time,
                logger=logger.plus_prefix("(%d,%d,%d): " % (N, sample, trial)))
            run_time = time.clock() - start_time

            # Update union of fxpts
            V = fx.sanitize_points(
                np.concatenate((fxpts, V), axis=1),
                f,
                ef,
                Df,
                duplicates=dups,
            )

            # Save results
            trace = solution["Fiber trace"]
            results[trial] = {
                "status": trace.status,
                "seconds": run_time,
                "|fxpts|": fxpts.shape[1],
                "|V|": V.shape[1],
            }
            results["trials"] = trial + 1
            data[str((trial, "c"))] = trace.c
            data[str((trial, "fxpts"))] = fxpts
            data["V"] = V

            sample_basename = "%s_p%d_N%d_s%d" % (basename, proc, N, sample)
            with open(sample_basename + ".pkl", 'w') as rf:
                pk.dump(results, rf)
            with open(sample_basename + ".npz", 'w') as df:
                np.savez(df, **data)

            print("%d,%d,%d,%d: status %s, |fxpts|=%d, |V|=%d" %
                  (proc, N, sample, trial, trace.status, fxpts.shape[1],
                   V.shape[1]))

            # Done if current c found full union
            if fxpts.shape[1] == V.shape[1]: break

            # Done if timeout
            if time.clock() > stop_time: break

        print("%d,%d,%d: %d trials" % (proc, N, sample, trial + 1))
        if time.clock() > stop_time: break

    proc_basename = "%s_p%d_N%d" % (basename, proc, N)
    with open(proc_basename + ".pkl", 'w') as rf:
        pk.dump({"num_samples": sample + 1}, rf)

    logfile.close()
예제 #4
0
def run_trial(args):
    basename, sample, timeout = args
    stop_time = time.clock() + timeout

    logfile = open("%s_s%d.log" % (basename, sample), "w")

    # Set up fiber arguments
    np.random.seed()
    v = 20 * np.random.rand(2, 1) - 10  # random point in domain
    c = lv.f(v)  # direction at that point
    c = c + 0.1 * np.random.randn(2, 1)  # perturb for more variability
    fiber_kwargs = {
        "f": lv.f,
        "ef": lv.ef,
        "Df": lv.Df,
        "compute_step_amount": lambda trace: (0.0001, 0),
        "v": v,
        "c": c,
        "stop_time": stop_time,
        "terminate": lambda trace: (np.fabs(trace.x[:-1]) > 10).any(),
        "max_solve_iterations": 2**5,
    }

    solve_start = time.clock()

    # Run in one direction
    solution = sv.fiber_solver(logger=lu.Logger(logfile).plus_prefix("+: "),
                               **fiber_kwargs)
    X1 = np.concatenate(solution["Fiber trace"].points, axis=1)
    V1 = solution["Fixed points"]
    z = solution["Fiber trace"].z_initial
    # print("Status: %s\n"%solution["Fiber trace"].status)

    # Run in other direction (negate initial tangent)
    solution = sv.fiber_solver(z=-z,
                               logger=lu.Logger(logfile).plus_prefix("-: "),
                               **fiber_kwargs)
    X2 = np.concatenate(solution["Fiber trace"].points, axis=1)
    V2 = solution["Fixed points"]
    # print("Status: %s\n"%solution["Fiber trace"].status)

    # Join fiber segments
    fiber = np.concatenate((np.fliplr(X1), X2), axis=1)

    # Union solutions
    fxpts = fx.sanitize_points(
        np.concatenate((V1, V2), axis=1),
        f=lv.f,
        ef=lv.ef,
        Df=lv.Df,
        duplicates=lambda V, v: (np.fabs(V - v) < 10**-6).all(axis=0),
    )

    # Save results
    with open("%s_s%d.npz" % (basename, sample), 'w') as rf:
        np.savez(
            rf, **{
                "fxpts": fxpts,
                "fiber": fiber,
                "runtime": time.clock() - solve_start
            })

    logfile.close()
예제 #5
0
    z = solution["Fiber trace"].z_initial

    # Run in other direction (negate initial tangent)
    fiber_kwargs["z"] = -z
    solution = sv.fiber_solver(**fiber_kwargs)
    V2 = np.concatenate(solution["Fiber trace"].points, axis=1)[:N, :]
    V2_fx = solution["Fixed points"]

    # Join fiber segments and fixed points
    V = np.concatenate((np.fliplr(V1), V2), axis=1)
    V_fx = np.concatenate((V1_fx, V2_fx), axis=1)

    fxpts = fx.sanitize_points(
        V_fx,
        f,
        ef,
        Df,
        duplicates=lambda V, v: (np.fabs(V - v) < 10**-6).all(axis=0),
    )

    print("Fxpts:")
    print(fxpts)
    print("Residuals:")
    print(ef(fxpts))

    # Visualize fiber if 2d
    if N == 2:
        X_f, Y_f = np.mgrid[-2:2:15j, -2:2:15j]
        V = V[:, \
            (V[0,:] >= X_f.min()) & \
            (V[0,:] <= X_f.max()) & \
예제 #6
0
def run_trial(args):
    basename, N, sample, W, V, timeout = args

    logfile = open(trialname(basename,N,sample)+".log", "w")
    logger = lu.Logger(logfile)

    # Sample network
    f = rnn.f_factory(W)
    Df = rnn.Df_factory(W)
    ef = rnn.ef_factory(W)

    # Run fiber solver
    solve_logger = logger.plus_prefix("(%d,%d): "%(N,sample))
    stop_time = time.clock() + timeout
    fxpts, solution = rnn.run_fiber_solver(W,
        # max_traverse_steps = 2**15,
        stop_time = stop_time,
        logger=solve_logger,
        abs_alpha_min = True,
        within_fiber = True)
    status = solution["Fiber trace"].status

    # Get pre-refinement sign change candidates
    sign_changes = solution["Sign changes"]
    refinements = solution["Refinements"]
    candidates = np.concatenate( # first refinement fiber point
        [refinements[sc].points[0][:-1,:] for sc in sign_changes],
        axis = 1)

    # Post-process sign change candidates
    logger.log("(%d,%d): Sanitizing %d sc points\n"%(
        N,sample, 2*candidates.shape[1] + 1))
    sign_change_fxpts = fx.sanitize_points(
        np.concatenate(
            (-candidates, np.zeros((N,1)), candidates),
            axis=1),
        f, ef, Df,
        duplicates = rnn.duplicates_factory(W),
    )

    # Count union
    logger.log("(%d,%d): Sanitizing %d+%d=%d union points\n"%(
        N,sample, fxpts.shape[1], sign_change_fxpts.shape[1],
        fxpts.shape[1] + sign_change_fxpts.shape[1]))
    union_fxpts = fx.sanitize_points(
        np.concatenate(
            (fxpts, sign_change_fxpts),
            axis=1),
        f, ef, Df,
        duplicates = rnn.duplicates_factory(W),
    )

    logfile.close()

    print("(%d,%d) fxpt counts: new %d, old %d, union %d (status=%s)"%(
        N,sample,fxpts.shape[1], sign_change_fxpts.shape[1],
        union_fxpts.shape[1], status))
        
    results = {
        "status": status,
        "new count": fxpts.shape[1],
        "old count":  sign_change_fxpts.shape[1],
        "union": union_fxpts.shape[1],
        }

    with open(trialname(basename,N,sample)+".pkl",'w') as rf:
        pk.dump(results, rf)
예제 #7
0
terminate = lambda trace: (np.fabs(trace.x) > 10**6).any()

compute_step_amount = lambda trace: (10**-3, None, False)

import dfibers.solvers as sv
# help(tv.traverse_fiber)
# help(sv.fiber_solver)
solution = sv.fiber_solver(
    f,
    ef,
    Df,
    compute_step_amount,
    v = np.zeros((N,1)),
    terminate=terminate,
    max_traverse_steps=10**3,
    max_solve_iterations=2**5,
    )

duplicates = lambda U, v: (np.fabs(U - v) < 2**-21).all(axis=0)

import dfibers.fixed_points as fx
V = solution["Fixed points"]
V = fx.sanitize_points(V, f, ef, Df, duplicates)

print("Fixed points:")
print(V)
print("Fixed point residuals:")
print(f(V))
assert((f(V) < ef(V)).all())