Exemplo n.º 1
0
def financeDataTest():
    pass
    df = pd.read_sql('SELECT * FROM AssetsRets',
                     conn).set_index('Dates', drop=True).iloc[-500:]
    df = df[['Nasdaq', 'DAX', 'USDEUR']]
    X = df.values
    #X = sl.cs(df[['Nasdaq', 'DAX', 'USDEUR']]).values
    print(X)

    dmd = DMD(svd_rank=2)
    dmd.fit(X.T)

    for eig in dmd.eigs:
        print('Eigenvalue {}: distance from unit circle {}'.format(
            eig, np.abs(eig.imag**2 + eig.real**2 - 1)))

    #dmd.plot_eigs(show_axes=True, show_unit_circle=True)

    modeList = []
    for mode in dmd.modes.T:
        modeList.append(mode)
        #plt.plot(x, mode.real)
        #plt.title('Modes')
    pd.DataFrame(modeList).plot()
    plt.show()

    for dynamic in dmd.dynamics:
        print(dynamic)
def _compute_dmd(frames, svd_rank):
    if len(frames.shape) == 4:  #if from color image
        vec_frames = np.reshape(frames, (frames.shape[0], frames.shape[1] *
                                         frames.shape[2] * frames.shape[3]))
    else:  #if from greyscale image
        vec_frames = np.reshape(
            frames, (frames.shape[0], frames.shape[1] * frames.shape[2]))
    dmd = DMD(svd_rank=svd_rank)
    #print("input is nan: " + str(np.isnan(vec_frames).any()))
    #print("input is inf: " + str(np.isinf(vec_frames).any()))
    vec_frames /= 255.0
    dmd.fit(np.nan_to_num(vec_frames.T, posinf=255, neginf=0))
    modes = dmd.modes.real
    return modes
Exemplo n.º 3
0
def test():
    def f1(x, t):
        return 1. / np.cosh(x + 3) * np.exp(2.3j * t)

    def f2(x, t):
        return 2. / np.cosh(x) * np.tanh(x) * np.exp(2.8j * t)

    x = np.linspace(-5, 5, 128)
    t = np.linspace(0, 4 * np.pi, 256)

    xgrid, tgrid = np.meshgrid(x, t)

    X1 = f1(xgrid, tgrid)
    X2 = f2(xgrid, tgrid)
    X = X1 + X2
    titles = ['$f_1(x,t)$', '$f_2(x,t)$', '$f$']
    data = [X1, X2, X]

    fig = plt.figure(figsize=(17, 6))
    for n, title, d in zip(range(131, 134), titles, data):
        plt.subplot(n)
        plt.pcolor(xgrid, tgrid, d.real)
        plt.title(title)
    plt.colorbar()
    plt.show()

    dmd = DMD(svd_rank=2)
    dmd.fit(X.T)

    for eig in dmd.eigs:
        print('Eigenvalue {}: distance from unit circle {}'.format(
            eig, np.abs(eig.imag**2 + eig.real**2 - 1)))

    #dmd.plot_eigs(show_axes=True, show_unit_circle=True)

    for mode in dmd.modes.T:
        plt.plot(x, mode.real)
        plt.title('Modes')
    plt.show()

    for dynamic in dmd.dynamics:
        plt.plot(t, dynamic.real)
        plt.title('Dynamics')
    plt.show()
Exemplo n.º 4
0
    def __init__(self, observables=None, differentiator=None, regressor=None):
        if observables is None:
            observables = Identity()
        if differentiator is None:
            differentiator = FiniteDifference()
        if regressor is None:
            regressor = DMD()

        self.observables = observables
        self.differentiator = differentiator
        self.regressor = regressor
Exemplo n.º 5
0
    def __init__(self, observables=None, regressor=None):
        if observables is None:
            observables = Identity()
        if regressor is None:
            regressor = DMD(svd_rank=2)
        if isinstance(regressor, DMDBase):
            regressor = DMDRegressor(regressor)
        elif not isinstance(regressor, (BaseRegressor)):
            raise TypeError("Regressor must be from valid class")

        self.observables = observables
        self.regressor = regressor
Exemplo n.º 6
0
    def __init__(self, observables=None, regressor=None, dt_default=1):
        if observables is None:
            observables = Polynomial(degree=1)
        if regressor is None:
            regressor = DMD()
        if not isinstance(dt_default, float) and not isinstance(dt_default, int):
            raise ValueError("dt_default must be a positive number")
        elif dt_default <= 0:
            raise ValueError("dt_default must be a positive number")
        else:
            self.dt_default = dt_default

        self.observables = observables
        self.regressor = regressor
Exemplo n.º 7
0
    def test_select_modes(self):
        def stable_modes(dmd_object):
            toll = 1e-3
            return np.abs(np.abs(dmd_object.eigs) - 1) < toll

        dmd = DMD(svd_rank=10)
        dmd.fit(sample_data)
        exp = dmd.reconstructed_data
        dmd.select_modes(stable_modes)
        np.testing.assert_array_almost_equal(exp, dmd.reconstructed_data)
Exemplo n.º 8
0
    def __init__(
        self, observables=None, differentiator=None, regressor=None, dt_default=1
    ):
        if observables is None:
            observables = Identity()
        if differentiator is None:
            differentiator = Derivative(kind="finite_difference", k=1)
        if regressor is None:
            regressor = DMD()
        if not isinstance(dt_default, float) and not isinstance(dt_default, int):
            raise ValueError("dt_default must be a positive number")
        elif dt_default <= 0:
            raise ValueError("dt_default must be a positive number")
        else:
            self.dt_default = dt_default

        self.observables = observables
        self.differentiator = differentiator
        self.regressor = regressor
Exemplo n.º 9
0
def predict(mu, t, params, dataset, dyas=True):
    if dyas:
        params = params[:, [1, 2, 3, 6, 7, 8]]
        mu = mu[[1, 2, 3, 6, 7, 8]]

    dmd = DMD(svd_rank=10)
    dmd.fit(dataset)
    dmd.original_time['t0'] = 12000
    dmd.original_time['tend'] = 20000
    dmd.original_time['dt'] = 1
    dmd.dmd_time['tend'] = t

    future_state = dmd.reconstructed_data.real[:, -1]  # output at t = t s

    kernel = GPy.kern.RBF(input_dim=params.shape[1],
                          variance=1.,
                          lengthscale=1.)
    model = GPy.models.GPRegression(params,
                                    future_state.reshape(-1, 1),
                                    kernel,
                                    normalizer=True)
    model.optimize_restarts(num_restarts=10, verbose=False)

    return model.predict(np.atleast_2d(mu))[0][0][0]
Exemplo n.º 10
0
def main():
    # when on cylon to test on full vid fdir = '../data/vid.tif'
    # when local test use 'short_vid.tif'
    vid = ca_data_utils.load_vid()
    X1 = flatten[:, :-1]
    X2 = flatten[:, 1:]

    print('start dmd')
    dmd = DMD(svd_rank=10)
    dmd.fit(flatten.T)
    print('finished fitting data')

    for eig in dmd.eigs:
        print('Eigenvalue {}: distance from unit circle {}'.format(
            eig, np.abs(eig.imag**2 + eig.real**2 - 1)))
    dmd.plot_eigs(show_axes=True, show_unit_circle=True)

    self_re = np.load('reconstructed.npy')
    diff = dmd.reconstructed_data.T - self_re

    print(len(np.where(np.abs(diff) > 1e-3)[0]))
    print(diff.max())
    print(diff.min())
            color=cmap(i / 10),
            marker=".",
            linestyle="-",
            label="mode {:.0f}".format(i))

plt.legend()
plt.title("coefficients of the first modes")
ax.set_xlabel("time")
ax.set_ylabel("right singular value")

plt.xlim(0, 1)
plt.ylim(X[:, :r].min(), X[:, :r].max())
plt.savefig(path + "DMD8Modes.png", dpi=250)
plt.close()

dmd = DMD(svd_rank=r)
dmd.fit(X.T)  # expected shape = (65, 129) = (spacial, time)

for eig in dmd.eigs:
    print('Eigenvalue {}: distance from unit circle {}'.format(
        eig, np.abs(np.sqrt(eig.imag**2 + eig.real**2) - 1)))

fig, ax = plt.subplots()
dmd.plot_eigs(show_axes=True, show_unit_circle=True)
plt.savefig(path + "DMDeigs.png", dpi=250)
plt.close()

fig, ax = plt.subplots()
for i, mode in enumerate(dmd.modes.T):
    # print(i)
    if i < 10:
X1 = f1(xgrid, tgrid)
X2 = f2(xgrid, tgrid)
X = X1 + X2

titles = ['$f_1(x,t)$', '$f_2(x,t)$', '$f$']
data = [X1, X2, X]

fig = plt.figure(figsize=(17, 6))
for n, title, d in zip(range(131, 134), titles, data):
    plt.subplot(n)
    plt.pcolor(xgrid, tgrid, d.real)
    plt.title(title)
plt.colorbar()
plt.show()

dmd = DMD(svd_rank=2)
dmd.fit(X.T)

for eig in dmd.eigs:
    print('Eigenvalue {}: distance from unit circle {}'.format(
        eig, np.abs(np.sqrt(eig.imag**2 + eig.real**2) - 1)))

dmd.plot_eigs(show_axes=True, show_unit_circle=True)

for mode in dmd.modes.T:
    plt.plot(x, mode.real)
    plt.title('Modes')
plt.show()

for dynamic in dmd.dynamics:
    plt.plot(t, dynamic.real)
Exemplo n.º 13
0
des_list_last = []
p1 = []
p2 = []
counter = -1
warp_flags = cv2.INTER_LANCZOS4
diff_factor = 255

# dmd options and structures
rows = 4
cols = 4
max_rank = ((rows * cols) * 2) - 2
print("max rank:", max_rank)
dmd_size = 200
window_size = 77
X = []
dmd = DMD(svd_rank=max_rank)


def draw_text(img, label, x, y, subscale=1.0, just="center"):
    font_scale = subscale * h / 700
    size = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, 1)
    if just == "center":
        locx = int(x - size[0][0] * 0.5)
        locy = int(y + size[0][1] * 1.5)
    elif just == "lower-right":
        locx = int(x - size[0][0])
        locy = int(y - size[0][1] * 0.5)
    elif just == "upper-right":
        locx = int(x - size[0][0])
        locy = int(y + size[0][1])
    elif just == "right":
Exemplo n.º 14
0
    from dolfin import XDMFFile, inner, grad, dx, assemble
    from interpreter import Eval
    # Build a monomial basis for x, y, x**2, xy, y**2, ...

    try:
        from pydmd import DMD
        # https://github.com/mathLab/PyDMD
    except ImportError:
        from xcalc.dmdbase import DMD

    deg = 4

    mesh = UnitSquareMesh(3, 3)
    V = FunctionSpace(mesh, 'CG', 1)
    f = interpolate(Expression('x[0]+x[1]', degree=1), V).vector().get_local()
    A = np.diag(np.random.rand(V.dim()))

    basis = []
    for i in range(deg):
        for j in range(deg):
            f = A.dot(f)
            Af = Function(V); Af.vector().set_local(f)
            basis.append(Af)
            
    # NOTE: skipping 1 bacause Eval of it is not a Function
    dmd_ = DMD(svd_rank=-1, exact=False)
    energy, pod_basis = dmd(basis[1:], dmd_)

    print np.linalg.norm(dmd_.snapshots - dmd_.reconstructed_data.real)
    print len(pod_basis), len(basis[1:])
Exemplo n.º 15
0
snapshots = [d+n for d,n in zip(data, noise)]

fig = plt.figure(figsize=(18,12))
for id_subplot, snapshot in enumerate(snapshots, start=1):
    plt.subplot(4, 4, id_subplot)
    plt.pcolor(x1grid, x2grid, snapshot.real, vmin=-1, vmax=1)


# Alright, now it is time to apply the DMD to the collected data. First, we create a new `DMD` instance; we note there are four optional parameters:
# - `svd_rank`: since the dynamic mode decomposition relies on *singular value decomposition*, we can specify the number of the largest singular values used to approximate the input data.
# - `tlsq_rank`: using the total least square, it is possible to perform a linear regression in order to remove the noise on the data; because this regression is based again on the singular value decomposition, this parameter indicates how many singular values are used.
# - `exact`: boolean flag that allows to choose between the exact modes or the projected one.
# - `opt`: boolean flag that allows to choose between the standard version and the optimized one.

dmd = DMD(svd_rank=1, tlsq_rank=2, exact=True, opt=True)
dmd.fit(snapshots)
dmd.plot_modes_2D(figsize=(12,5))


# The `svd_rank` can be set to zero for an automatic selection of the truncation rank; in some cases (as this tutorial) the singular values should be examinated in order to select the proper truncation.

fig = plt.plot(scipy.linalg.svdvals(np.array([snapshot.flatten() for snapshot in snapshots]).T), 'o')



fig = plt.figure(figsize=(18,12))
for id_subplot, snapshot in enumerate(dmd.reconstructed_data.T, start=1):
    plt.subplot(4, 4, id_subplot)
    plt.pcolor(x1grid, x2grid, snapshot.reshape(x1grid.shape).real, vmin=-1, vmax=1)
Exemplo n.º 16
0
def rank_sensitvity(dsys, x_train, n_test=100):
    """
    This function using the generated training dataset to fit DMD and OptDMD models of increasing rank.
    It also computes the test error on an ensemble of testing dataset to get a better estimation of the
    generalization capabilities of the fitted models.

    Parameters
    ----------

    dsys : scipy.signal.dlti
        The discrete LTI system considered.

    x_train : array-like, shape (n_features, n_samples)
        The training dataset.
        NOTE : It is transposed compared to the output of dsys.

    n_test : int
        The number of testing datasets to be generated.

    Returns
    -------

    dmd_train_error : array-like, shape (n_ranks,)
        The reconstruction error of the DMD model on the training data.

    dmd_test_error : array-like, shape (n_ranks, n_test)
        The reconstruction error of the DMD model on the various testing datasets.

    optdmd_train_error : array-like, shape (n_ranks,)
        The reconstruction error of the OptDMD model on the training data.

    optdmd_test_error : array-like, shape (n_ranks, n_test)
        The reconstruction error of the OptDMD model on the various testing datasets.


    """

    dmd_train_error, optdmd_train_error = list(), list()
    dmd_test_error, optdmd_test_error = list(), list()

    #  Split the training data into input/output snapshots.
    y_train, X_train = x_train[:, 1:], x_train[:, :-1]

    for rank in range(1, dsys.A.shape[0] + 1):

        # Fit the DMD model (Schmid's algorithm)
        dmd = DMD(svd_rank=rank).fit(x_train)

        # Fit the DMD model (optimal closed-form solution)
        optdmd = OptDMD(svd_rank=rank, factorization="svd").fit(x_train)

        # One-step ahead prediction using both DMD models.
        y_predict_dmd = dmd.predict(X_train)
        y_predict_opt = optdmd.predict(X_train)

        # Compute the one-step ahead prediction error.
        dmd_train_error.append(norm(y_predict_dmd - y_train) / norm(y_train))
        optdmd_train_error.append(
            norm(y_predict_opt - y_train) / norm(y_train))

        # Evaluate the error on test data.
        dmd_error, optdmd_error = list(), list()
        for _ in range(n_test):
            # Test initial condition.
            x0_test = normal(loc=0.0, scale=1.0, size=(dsys.A.shape[1]))

            # Run simulation to generate dataset.
            t, _, x_test = dlsim(dsys,
                                 np.zeros((250, dsys.inputs)),
                                 x0=x0_test)

            # Split the training data into input/output snapshots.
            y_test, X_test = x_test.T[:, 1:], x_test.T[:, :-1]

            # One-step ahead prediction using both DMD models.
            y_predict_dmd = dmd.predict(X_test)
            y_predict_opt = optdmd.predict(X_test)

            # Compute the one-step ahead prediction error.
            dmd_error.append(norm(y_predict_dmd - y_test) / norm(y_test))
            optdmd_error.append(norm(y_predict_opt - y_test) / norm(y_test))

        # Store the error for rank i DMD.
        dmd_test_error.append(np.asarray(dmd_error))
        optdmd_test_error.append(np.asarray(optdmd_error))

    # Complete rank-sensitivity.
    dmd_test_error = np.asarray(dmd_test_error)
    optdmd_test_error = np.asarray(optdmd_test_error)

    dmd_train_error = np.asarray(dmd_train_error)
    optdmd_train_error = np.asarray(optdmd_train_error)

    return dmd_train_error, dmd_test_error, optdmd_train_error, optdmd_test_error
    plt.show()



    # PLOT Principal Components of time dynamics
    num_pcs = 1

    plt.figure(146)
    for i, neuron in enumerate(neuron_numbers):
        plt.subplot(plot_rows, plot_cols, i+1)
        plt.title('RNN representation (Neuron {})'.format(neuron))
        plt.xlabel('Frame number')
        plt.ylabel('Neuron Activation')
        
#        [u, s, v] = np.linalg.svd(rnn_representation[:, :, neuron].T, full_matrices=False)
        dmd = DMD(svd_rank = num_pcs)
        dmd.fit(rnn_representation[:, :, neuron].T)


        for mode in dmd.modes.T:
#            plt.plot(u[i, :])
            plt.plot(mode.real)
             

        plt.legend(['Mode {}'.format(k+1) for k in range(num_pcs)])
        
    plt.show()


    plt.figure(1445)
    for i, neuron in enumerate(neuron_numbers):
import numpy as np
from dmd_utils import getVideoFrames, shape_frames
from pydmd import DMD, MrDMD
shape = (540,960,3)
frames = getVideoFrames('data/test_video.webm', (75,200))
dmd = DMD(svd_rank=6)
dmd.fit(frames.T)
mrdmd = MrDMD(svd_rank=6, max_level=4, max_cycles=1)
mrdmd.fit(frames.T.astype(np.float64))

dmd_frames = dmd.reconstructed_data.real.T.astype(np.uint8)
shape_frames(dmd_frames,"data/dmd_test.avi",shape)

for i in range(4):
    mrdmd_frames = mrdmd.partial_reconstructed_data(i).real.T.astype(np.uint8)
    shape_frames(mrdmd_frames,"data/mrdmd_level%d_test.avi"%i, shape)
mrdmd_frames = mrdmd.reconstructed_data.real.T.astype(np.uint8)
shape_frames(mrdmd_frames,"data/mrdmd_all_test.avi",shape)

Exemplo n.º 19
0
model.summary()

# reshape x_train, x_test to fit input in LSTM layers
X_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
X_test = np.reshape(x_test, (x_test.shape[0], 1, x_test.shape[1]))

%%time
model.fit(x = X_train, y = y_train,
                    epochs=5,
                    steps_per_epoch=10)

predictions = model.predict(X_test)
predictions = predictions.reshape(test_size,2)
koopman_pred = predictions.T

dmd = DMD(svd_rank=2)
dmd.fit(koopman_pred)
dmd_eigs = dmd.eigs
dmd_modes = dmd.modes
dmd_dynamics = dmd.dynamics

x = dmd_dynamics[0]
y = dmd_dynamics[1]

fig = plt.figure()
ax = fig.gca(projection='3d')

# PLOTTING
print(ax.plot_trisurf(range(3000), x, y))
print(plt.contour(dmd_modes))
print(plt.contour(dmd_dynamics))
Exemplo n.º 20
0
            payoffs = generateGames(Gamma, nSim, nActions)
            allActions = []

            qValues0 = np.random.rand(2, nActions, nSim)

            for cIter in range(nIter):
                qValues0 = qUpdate(qValues0, payoffs)

                if cIter >= 0:

                    allActions += [
                        stringActions(getActionProbs(qValues0, nSim))
                    ]

                    if cIter == 30:
                        dmd = DMD(svd_rank=-1)

                        dmd.fit(np.array(allActions).T)
                        dmd.plot_eigs()
                        plt.show()

                    if cIter == 100:
                        dmd = DMD(svd_rank=-1)

                        dmd.fit(np.array(allActions).T)
                        dmd.plot_eigs()
                        plt.show()

                    if cIter == 1000:
                        dmd = DMD(svd_rank=-1)
def getModes(sequence):
    dmd = DMD(svd_rank=6)
    dmd.fit(sequence.T)
    return dmd.modes
Exemplo n.º 22
0
pts = np.genfromtxt('data/velocity0.20.csv', delimiter=',', skip_header=1)[:, -3:-1]


plt.figure(figsize=(16, 16))
for i, snapshot in enumerate(snapshots[::5], start=1):
    plt.subplot(2, 2, i)
    plt.scatter(pts[:, 0], pts[:, 1], c=snapshot, marker='.')
plt.show()

fbdmd = FbDMD(exact=True)
fbdmd.fit(snapshots)
fbdmd.reconstructed_data.shape


dmd = DMD(exact=True)
dmd.fit(snapshots)

print('[DMD  ] Total distance between eigenvalues and unit circle: {}'.format(
    np.sum(np.abs(dmd.eigs.real**2 + dmd.eigs.imag**2 - 1))
))
print('[FbDMD] Total distance between eigenvalues and unit circle: {}'.format(
    np.sum(np.abs(fbdmd.eigs.real**2 + fbdmd.eigs.imag**2 - 1))
))

dmd.plot_eigs()
fbdmd.plot_eigs()


fbdmd.dmd_time['dt'] *= .5
fbdmd.dmd_time['tend'] += 10
Exemplo n.º 23
0
# We instantiate the `cDMD` matrix, passing as `compression_matrix` argument the matrix we created. The constructor is very similar to the `DMD` class, except to the compression matrix and the missing of the `exact` argument (in the compressed version, there is only one way to compute the modes). We plot the modes and the dynamics.

cdmd = CDMD(svd_rank=3, compression_matrix=compression_matrix)
cdmd.fit(snapshots_matrix)

plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1)
plt.plot(cdmd.modes.real)
plt.subplot(1, 2, 2)
plt.plot(cdmd.dynamics.T.real)
plt.show()

# In order to investigate about the reconstruction accuracy, we compare the results obtained with the cDMD and the standard DMD, respectively.

dmd = DMD(svd_rank=3, exact=True)
dmd.fit(snapshots_matrix)

dmd_error = np.linalg.norm(snapshots_matrix - dmd.reconstructed_data)
cdmd_error = np.linalg.norm(snapshots_matrix - cdmd.reconstructed_data)
print("DMD error: {}".format(dmd_error))
print("CDMD error: {}".format(cdmd_error))

plt.figure(figsize=(16, 8))
plt.subplot(1, 3, 1)
plt.title('Original snapshots')
plt.pcolor(xgrid, tgrid, snapshots_matrix.real.T)
plt.subplot(1, 3, 2)
plt.title('Reconstructed with DMD')
plt.pcolor(xgrid, tgrid, dmd.reconstructed_data.real.T)
plt.subplot(1, 3, 3)
Exemplo n.º 24
0
 def test_integral_contribution_reconstruction(self):
     dmd = DMD(svd_rank=10)
     dmd.fit(sample_data)
     exp = dmd.reconstructed_data
     dmd.select_modes(DMDBase.ModesSelectors.integral_contribution(2))
     np.testing.assert_array_almost_equal(exp, dmd.reconstructed_data)
Exemplo n.º 25
0
    def run_dmd(self):
        def _plot_future_state():
            print("Shape before manipulation: {}".format(
                dmd.reconstructed_data.shape))
            dmd.dmd_time['tend'] *= 40
            print("Shape after manipulation: {}".format(
                dmd.reconstructed_data.shape))
            new_num_frames = dmd.reconstructed_data.shape[1]
            new_time = np.linspace(1, new_num_frames, new_num_frames)

            atom_axis, time_axis = np.meshgrid(new_time, atoms)
            plt.figure(figsize=(7, 8))
            plt.title("Projection with DMD")
            plt.pcolormesh(time_axis, atom_axis, dmd.reconstructed_data.real)
            plt.xlabel("Atom Index")
            plt.ylabel("Frame")
            plt.colorbar()
            plt.show()

        def _plot_data():
            atom_axis, time_axis = np.meshgrid(time, atoms)

            plt.figure(figsize=(7, 8))
            plt.subplot(2, 1, 1)
            plt.title("Original PDB data")
            plt.pcolormesh(time_axis, atom_axis, snapshot_matrix)
            plt.xlabel("Atom Index")
            plt.ylabel("Frame")
            plt.colorbar()
            plt.subplot(2, 1, 2)
            plt.title("Reconstructed with DMD")
            plt.pcolormesh(time_axis, atom_axis, dmd.reconstructed_data.real)
            plt.xlabel("Atom Index")
            plt.ylabel("Frame")
            plt.colorbar()
            plt.show()

        def _plot_modes():
            plt.figure(figsize=(8, 8))
            for mode in dmd.modes.T:
                plt.plot(atoms, mode)
                plt.title('Modes')
            plt.show()

        def _plot_dynamics():
            plt.figure(figsize=(8, 8))
            for dynamic in dmd.dynamics:
                plt.plot(time, dynamic)
                plt.title('Dynamics')
            plt.show()

        def _print_eigs():
            for eig in dmd.eigs:
                dist = np.abs(eig.imag**2 + eig.real**2 - 1)
                print("Eigenvalue:", eig, " Distance from unit circle:", dist)

        def _plot_eigs():
            dmd.plot_eigs(show_axes=True, show_unit_circle=True)

        def _print_error():
            # error = np.linalg.norm((snapshot_matrix - dmd.reconstructed_data))
            error = (np.square((snapshot_matrix -
                                dmd.reconstructed_data).real)).mean(axis=None)
            print("DMD error:", error)

        def _plot_error():
            plt.pcolormesh(
                time, atoms,
                np.divide((snapshot_matrix - dmd.reconstructed_data).real,
                          snapshot_matrix))
            plt.colorbar()
            plt.show()

        self.data = []  # TODO: DANGEROUS PLEASE REMOVE (TESTING ONLY)
        self._get_hilbert()  # updates self.data[]

        snapshot_matrix = np.array(self.data).transpose()

        dmd = DMD(svd_rank=.97, tlsq_rank=2, exact=True,
                  opt=True)  # create instance of DMD object
        dmd.fit(snapshot_matrix)  # populate the matrix with data

        num_atoms = len(self.data[0])
        num_frames = len(snapshot_matrix[0])

        atoms = np.linspace(1, num_atoms, num_atoms)
        time = np.linspace(1, num_frames, num_frames)

        # _plot_future_state()
        _plot_data()
Exemplo n.º 26
0
# -*- coding: utf-8 -*-
"""
Created on Thu Feb  7 16:25:16 2019

@author: Colton Smith
"""

import numpy as np
from pydmd import DMD

vals = np.array([[-2, 6, 1, 1, -1], [-1, 5, 1, 2, -1], [0, 4, 2, 1, -1],
                 [1, 3, 2, 2, -1], [2, 2, 3, 1, -1], [3, 1, 3, 2, -1]])

dmd = DMD(svd_rank=2)
vals_sub = vals[:5, :]
dmd.fit(vals_sub.T)
dmd.dmd_time['tend'] *= (1 + 1 / 6)
recon = dmd.reconstructed_data.real.T

print('Actual :', vals[5, :])
print('Predicted :', recon[5, :])
Exemplo n.º 27
0
import numpy as np
from pydmd import DMD
from PIL import Image
from dmd_utils import getVideoFrames

X = getVideoFrames('data/MOT16-09-raw.webm', (100, 105))
dmd = DMD(svd_rank=6)
print("X shape: " + str(X.T.shape))
print("X avg: " + str(np.average(X)))
X = X.astype(np.float64)
dmd.fit(X.T)
print(dmd.reconstructed_data.real.shape)
print(dmd.modes.real.shape)
print(dmd.dynamics.real.shape)
post_dmd = np.reshape(dmd.reconstructed_data.T.real[0].astype(np.uint8),
                      (540, 960, 3))
new_image = Image.fromarray(post_dmd, 'RGB')
new_image.show(title='after compression')
count = 0
for mode in abs(dmd.modes.T.real):
    image = Image.fromarray(
        np.reshape((mode * 255 / max(mode)).astype(np.uint8), (540, 960, 3)),
        'RGB')
    image.show("mode #" + str(count))
    count += 1
Exemplo n.º 28
0
    plt.xlabel('Space')
    plt.ylabel('Time')
    plt.show()


# Let us start by creating the dataset and plot the data in order to have a first idea of the problem.

sample_data = create_sample_data()
x = np.linspace(-10, 10, 80)
t = np.linspace(0, 20, 1600)
make_plot(sample_data.T, x=x, y=t)


# First we apply the classical DMD without the svd rank truncation, and then we try to reconstruct the data. You can clearly see that all the transient time events are missing.

first_dmd = DMD(svd_rank=-1)
first_dmd.fit(X=sample_data)
make_plot(first_dmd.reconstructed_data.T, x=x, y=t)


# Now we do the same but using the mrDMD instead. The result is remarkable even with the svd rank truncation (experiment changing the input parameters).

sub_dmd = DMD(svd_rank=-1)
dmd = MrDMD(sub_dmd, max_level=7, max_cycles=1)
dmd.fit(X=sample_data)
make_plot(dmd.reconstructed_data.T, x=x, y=t)


# We now plot the eigenvalues in order to better understand the mrDMD. Without truncation we have 80 eigenvalues.

import numpy as np
import scipy
import scipy.integrate

from matplotlib import animation
from IPython.display import HTML
from matplotlib import pyplot as plt
from pydmd import DMD
from pydmd import FbDMD

A = np.loadtxt('dmd.txt', delimiter=",")
B = A.T
C = B[:, 0:5000]

print(C.shape)
dmd = DMD(svd_rank=1, tlsq_rank=2, exact=True, opt=True)
dmd.fit(C)
fbdmd = FbDMD(exact=True)
fbdmd.fit(C)
print(fbdmd.reconstructed_data.shape)
fbdmd.dmd_time['dt'] *= .5
fbdmd.dmd_time['tend'] += 10

plt.plot(fbdmd.dmd_timesteps, fbdmd.dynamics.T.real)

plt.show()

print("Shape before manipulation: {}".format(dmd.reconstructed_data.shape))
dmd.dmd_time['dt'] *= .25
dmd.dmd_time['tend'] *= 3
print("Shape after manipulation: {}".format(dmd.reconstructed_data.shape))