示例#1
0
    N = int(T / dt)
    t = np.linspace(0., T, N)
    x = np.zeros(N)
    eps = np.random.randn(N)
    for n in range(N - 1):
        dU = 2. * x[n] * (b * x[n] ** 2 - c) * (3.* b * x[n] ** 2 - c) + 2. * a
        x[n + 1] = x[n] - dU * dt + sig * sqrt_dt * eps[n]

    # sample the true time series
    every = 250
    xs = x[::every]
    ts = t[::every]

    # get recurrence network adjacency
    print("recurrence network ...")
    A = rc.rn(xs, m=1, tau=1, e=0.20,
              norm="euclidean", threshold_by="frr", normed=True)

    # optimize modularity
    print("optimize modularity ...")
    G = ig.Graph.Adjacency(A.tolist(), mode=ig.ADJ_UNDIRECTED)
    dendro = G.community_fastgreedy()
    clust = dendro.as_clustering()
    mem = clust.membership
    clust_ids = np.unique(mem)

    # plot
    print("plot ...")
    # plot potential
    x_ = np.linspace(-3., 3., 1000)
    U = x_ ** 2 * (b * x_ ** 2 - c) ** 2 + a * x_ ** 2
    ax1.plot(U, x_, "-", c="0.5")
示例#2
0
def _get_data():
    """
    Estimates Lyapunov, DET, and SPL for Henon map.
    """
    # Henon map time series
    print("Henon map time series ...")
    t = np.arange(0, 10000, 1)
    a = np.linspace(1.0, 1.4, na).reshape(na, 1)
    b = 0.30
    nt = len(t)
    x, y = [np.zeros((nt, na, ns)) for i in range(2)]
    x[0, :, :] = 1E-1 * np.random.rand(na, ns)
    y[0, :, :] = 1E-1 * np.random.rand(na, ns)
    pb = _progressbar_start(max_value=nt, pbar_on=True)
    LPV = np.zeros((na, ns))
    for i in range(1, nt):
        x[i, :, :] = 1. - a * x[i - 1, :, :]**2 + y[i - 1, :, :]
        y[i, :, :] = b * x[i - 1, :, :]
        if i >= nt / 2:
            LPV[:, :] += np.log(np.fabs(-2. * a * x[i - 1, :, :]))
        _progressbar_update(pb, i)
    _progressbar_finish(pb)
    xH_eq = x[-neq:, :, :]
    LPV /= float(nt)

    # estimate embedding parameters
    print("embedding parameters ...")
    tau, m = np.ones(na, dtype="int"), 2 * np.ones(na, dtype="int")

    # DET
    print("DET ...")
    RR = 0.30
    DET = np.zeros((na, ns))
    pb = _progressbar_start(max_value=ns * na, pbar_on=True)
    k = 0
    for j in range(ns):
        for i in range(na):
            R = rc.rp(xH_eq[:, i, j],
                      m=m[i],
                      tau=tau[i],
                      e=RR,
                      norm="euclidean",
                      threshold_by="frr")
            DET[i, j] = rqa.det(R, lmin=2, hist=None, verb=False)
            del R
            _progressbar_update(pb, k)
            k += 1
    _progressbar_finish(pb)

    # SPL
    print("SPL ...")
    SPL = np.zeros((na, ns))
    pb = _progressbar_start(max_value=ns * na, pbar_on=True)
    k = 0
    for j in range(ns):
        for i in range(na):
            A = rc.rn(xH_eq[:, i, j],
                      m=m[i],
                      tau=tau[i],
                      e=RR,
                      norm="euclidean",
                      threshold_by="frr")
            G = ig.Graph.Adjacency(A.tolist(), mode=ig.ADJ_UNDIRECTED)
            pl_hist = G.path_length_hist(directed=False)
            SPL[i, j] = pl_hist.mean
            del A, G
            _progressbar_update(pb, k)
            k += 1
    _progressbar_finish(pb)

    # save output
    FN = DATPATH + "det_spl_lpv_na%d_ns%s_neq%d" % (na, ns, neq)
    np.savez(FN, DET=DET, SPL=SPL, LPV=LPV, t=t, a=a, b=b, x=x, y=y)
    print("saved to %s.npz" % FN)

    return None
示例#3
0
def _get_spl():
    """
    Estimates the average shortest path length SPL for the indices.
    """
    # load data
    utils._printmsg("load data ...", args.verbose)
    t, x_enso, x_pdo = _load_indices()
    x = {
        "enso": x_enso,
        "pdo": x_pdo,
    }
    names = ["enso", "pdo"]

    # get surrogates
    utils._printmsg("iAAFT surrogates ...", args.verbose)
    ns = args.nsurr
    SURR = {}
    for name in names:
        utils._printmsg("\t for %s" % name.upper(), args.verbose)
        SURR[name] = rc.surrogates(x[name], ns, "iaaft", verbose=args.verbose)

    # recurrence plot parameters
    EPS, LMIN = 0.30, 3
    thrby = "frr"

    # get SPL for original data
    utils._printmsg("SPL for original data ...", args.verbose)
    n = len(t)
    ws, ss = args.window_size, args.step_size
    nw = int(np.floor(float(n - ws) / float(ss)))
    tm = np.empty(nw, dtype="object")
    m, tau = {}, {}
    A = {}
    maxlag = 150
    maxdim = 20
    r_fnn = 0.0010
    SPL = {}
    for name in names:
        if args.verbose: print("\t for %s" % name.upper())
        # get embedding parameters
        ## get mi
        mi, mi_lags = rc.mi(x[name], maxlag, pbar_on=False)
        # mi, mi_lags = rc.acf(x[name], maxlag)
        mi_filt, _ = utils.boxfilter(mi, filter_width=3, estimate="mean")
        try:
            tau[name] = rc.first_minimum(mi_filt)
        except ValueError:
            tau[name] = 1
        ## FNN
        fnn, dims = rc.fnn(x[name],
                           tau[name],
                           maxdim=maxdim,
                           r=r_fnn,
                           pbar_on=False)
        m[name] = dims[rc.first_zero(fnn)]
        A[name] = rc.rn(
            x[name],
            m=m[name],
            tau=tau[name],
            e=EPS,
            norm="euclidean",
            threshold_by=thrby,
        )
        A_ = A[name]
        G_ = ig.Graph.Adjacency(A_.tolist(), mode=ig.ADJ_UNDIRECTED)
        nw = len(tm)
        spl = np.zeros(nw)
        pb = _progressbar_start(max_value=nw, pbar_on=args.verbose)
        for i in range(nw):
            start = i * ss
            end = start + ws
            Gw = G_.subgraph(vertices=G_.vs[start:end])
            pl_hist = Gw.path_length_hist(directed=False)
            spl[i] = pl_hist.mean
            tm[i] = t[start] + (t[end] - t[start]) / 2
            _progressbar_update(pb, i)
        _progressbar_finish(pb)
        SPL[name] = spl

    # get SPL for surrogate data
    utils._printmsg("SPL for surrogates ...", args.verbose)
    SPLSURR = {}
    for name in names:
        utils._printmsg("\tfor %s" % name.upper(), args.verbose)
        xs = SURR[name]
        y = np.diff(xs, axis=0)
        splsurr = np.zeros((ns, nw), dtype="float")
        pb = _progressbar_start(max_value=ns, pbar_on=args.verbose)
        for k in range(ns):
            As = rc.rp(
                xs[k],
                m=m[name],
                tau=tau[name],
                e=EPS,
                norm="euclidean",
                threshold_by=thrby,
            )
            Gs = ig.Graph.Adjacency(As.tolist(), mode=ig.ADJ_UNDIRECTED)
            for i in range(nw):
                start = i * ss
                end = start + ws
                Gw = Gs.subgraph(vertices=Gs.vs[start:end])
                pl_hist = Gw.path_length_hist(directed=False)
                splsurr[k, i] = pl_hist.mean
            _progressbar_update(pb, k)
        _progressbar_finish(pb)
        SPLSURR[name] = splsurr

    # get each individual array out of dict to avoid  NumPy import error
    SPL_enso = SPL["enso"]
    SPL_pdo = SPL["pdo"]
    SPLSURR_enso = SPLSURR["enso"]
    SPLSURR_pdo = SPLSURR["pdo"]
    SURR_enso = SURR["enso"]
    SURR_pdo = SURR["pdo"]
    tm = np.array([date.toordinal() for date in tm])

    # save output
    EPS = int(EPS * 100)
    FN = DATPATH + "spl_WS%d_SS%d_EPS%dpc_LMIN%d_NSURR%d" \
                   % (ws, ss, EPS, LMIN, ns)
    np.savez(FN,
             SPL_enso=SPL_enso,
             SPL_pdo=SPL_pdo,
             SPLSURR_enso=SPLSURR_enso,
             SPLSURR_pdo=SPLSURR_pdo,
             SURR_enso=SURR_enso,
             SURR_pdo=SURR_pdo,
             tm=tm)
    if args.verbose: print("output saved to: %s.npz" % FN)

    return None
示例#4
0
def _get_communities():
    """
    Identifies the optimal community structure based on modularity.
    """
    # load data
    utils._printmsg("load data ...", args.verbose)
    t, x_enso, x_pdo = _load_indices()
    x = {
        "enso": x_enso,
        "pdo": x_pdo,
    }
    names = ["enso", "pdo"]

    # recurrence plot parameters
    EPS = 0.30
    thrby = "frr"

    # embedding parameters
    utils._printmsg("embedding parameters ...", args.verbose)
    n = len(t)
    m, tau = {}, {}
    R = {}
    maxlag = 150
    maxdim = 20
    r_fnn = 0.0010
    for name in names:
        if args.verbose: print("\t for %s" % name.upper())
        # get embedding parameters
        ## get mi
        mi, mi_lags = rc.mi(x[name], maxlag, pbar_on=False)
        # mi, mi_lags = rc.acf(x[name], maxlag)
        mi_filt, _ = utils.boxfilter(mi, filter_width=3, estimate="mean")
        try:
            tau[name] = rc.first_minimum(mi_filt)
        except ValueError:
            tau[name] = 1
        ## FNN
        fnn, dims = rc.fnn(x[name],
                           tau[name],
                           maxdim=maxdim,
                           r=r_fnn,
                           pbar_on=False)
        m[name] = dims[rc.first_zero(fnn)]

    # # print out embedding dimensions for documentation in the paper
    # print m
    # print tau
    # sys.exit()

    # identify communities using modularity
    utils._printmsg("communities based on modularity ...", args.verbose)
    COMM = {}
    for name in names:
        utils._printmsg("\tfor %s" % name.upper(), args.verbose)
        A = rc.rn(x[name],
                  m=m[name],
                  tau=tau[name],
                  e=EPS,
                  norm="euclidean",
                  threshold_by="frr",
                  normed=True)

        # optimize modularity
        utils._printmsg("\toptimize modularity ...", args.verbose)
        G = ig.Graph.Adjacency(A.tolist(), mode=ig.ADJ_UNDIRECTED)
        dendro = G.community_fastgreedy()
        # dendro = G.community_edge_betweenness(directed=False)
        clust = dendro.as_clustering()
        # clust = G.community_multilevel()
        mem = clust.membership
        COMM[name] = mem

    # get each individual array out of dict to avoid  NumPy import error
    x_enso = x["enso"]
    x_pdo = x["pdo"]
    COMM_enso = COMM["enso"]
    COMM_pdo = COMM["pdo"]
    t = np.array([date.toordinal() for date in t])

    # save output
    EPS = int(EPS * 100)
    FN = DATPATH + "communities_EPS%d" \
                   % EPS
    np.savez(FN,
             x_enso=x_enso,
             x_pdo=x_pdo,
             t=t,
             COMM_enso=COMM_enso,
             COMM_pdo=COMM_pdo,
             m=m,
             tau=tau,
             e=EPS,
             thrby=thrby)
    if args.verbose: print("output saved to: %s.npz" % FN)

    return None
示例#5
0
def _get_data():
    """
    Estimates Lyapunov, DET, and SPL for Henon map.
    """
    # Henon map time series
    print("Henon map time series ...")
    t = np.arange(0, 10000, 1)
    a = np.linspace(1.28, 1.32, na).reshape(na, 1)
    j, k = (1 * na) / 8, ns / 2
    print "a = ", a[j]
    # sys.exit()
    b = 0.30
    nt = len(t)
    x, y = [np.zeros((nt, na, ns)) for i in range(2)]
    x[0, :, :] = 1E-2 * np.random.rand(na, ns)
    y[0, :, :] = 1E-2 * np.random.rand(na, ns)
    pb = _progressbar_start(max_value=nt, pbar_on=True)
    LPV = np.zeros((na, ns))
    for i in range(1, nt):
        x[i, :, :] = 1. - a * x[i - 1, :, :]**2 + y[i - 1, :, :]
        y[i, :, :] = b * x[i - 1, :, :]
        if i >= nt / 2:
            LPV[:, :] += np.log(np.fabs(-2. * a * x[i - 1, :, :]))
        _progressbar_update(pb, i)
    _progressbar_finish(pb)
    xH_eq = x[-neq:, :, :]
    LPV /= float(nt)

    print("RP ...")
    RR = 0.30
    y = xH_eq[:, j, k].flatten()
    R = rc.rp(y, m=2, tau=1, e=RR, norm="euclidean", threshold_by="frr")
    DET = rqa.det(R, lmin=2, hist=None, verb=False)
    print DET
    print("plot...")
    pl.subplot(211)
    pl.plot(y, alpha=0.5)
    pl.subplot(212)
    pl.imshow(R, cmap=pl.cm.gray_r, origin="lower", interpolation="none")
    pl.show()
    sys.exit()

    print("plot data ...")
    xplot = np.zeros((na, neq * ns))
    for i in range(na):
        xplot[i] = xH_eq[:, i, :].flatten()
    print("plot ...")
    fig = pl.figure(figsize=[21., 12.], facecolor="none")
    ax = fig.add_axes([0.10, 0.10, 0.80, 0.80])
    ax.plot(a,
            xplot,
            "o",
            ms=1.00,
            alpha=0.25,
            rasterized=True,
            mfc="k",
            mec="none")
    print("prettify ...")
    ax.tick_params(labelsize=14, size=8)
    ax.tick_params(size=5, which="minor")
    # ax.set_xticks(np.arange(1.0, 1.401, 0.05), minor=False)
    # ax.set_xticks(np.arange(1.0, 1.401, 0.01), minor=True)
    ax.grid(which="both")
    # ax.set_xlim(1.0, 1.4)
    print("save figure ...")
    FN = "../plots/" + __file__[2:-3] + ".png"
    fig.savefig(FN, rasterized=True, dpi=100)
    print("figure saved to: %s" % FN)
    sys.exit()

    # estimate embedding parameters
    print("embedding parameters ...")
    tau, m = np.ones(na, dtype="int"), 2 * np.ones(na, dtype="int")

    # DET
    print("DET ...")
    RR = 0.25
    DET = np.zeros((na, ns))
    pb = _progressbar_start(max_value=ns * na, pbar_on=True)
    k = 0
    for j in range(ns):
        for i in range(na):
            R = rc.rp(xH_eq[:, i, j],
                      m=m[i],
                      tau=tau[i],
                      e=RR,
                      norm="euclidean",
                      threshold_by="frr")
            DET[i, j] = rqa.det(R, lmin=2, hist=None, verb=False)
            del R
            _progressbar_update(pb, k)
            k += 1
    _progressbar_finish(pb)

    # SPL
    print("SPL ...")
    SPL = np.zeros((na, ns))
    pb = _progressbar_start(max_value=ns * na, pbar_on=True)
    k = 0
    for j in range(ns):
        for i in range(na):
            A = rc.rn(xH_eq[:, i, j],
                      m=m[i],
                      tau=tau[i],
                      e=RR,
                      norm="euclidean",
                      threshold_by="frr")
            G = ig.Graph.Adjacency(A.tolist(), mode=ig.ADJ_UNDIRECTED)
            pl_hist = G.path_length_hist(directed=False)
            SPL[i, j] = pl_hist.mean
            del A, G
            _progressbar_update(pb, k)
            k += 1
    _progressbar_finish(pb)

    # save output
    FN = DATPATH + "det_spl_lpv_na%d_ns%s_neq%d" % (na, ns, neq)
    np.savez(FN, DET=DET, SPL=SPL, LPV=LPV, t=t, a=a, b=b, x=x, y=y)
    print("saved to %s.npz" % FN)

    return None