def xs_compute_true_u(cb, nsamples, pi_line, kcmax=1, plot=False, write=False):
    X = np.zeros((n_inputs))
    y = np.zeros((1))

    for n in range(nsamples):
        for kc in range(1, kcmax + 1):
            filename = "cpx_init_kc%d_%d" % (kc, n)
            uu = harm.complex_init_sin(cb.line_x,
                                       kc=kc,
                                       inter_deph=pi_line,
                                       L=cb.L,
                                       plot=plot)
            _, abs_work = LW_solver(uu,
                                    cb.itmax,
                                    filename=filename,
                                    write=write,
                                    plot=plot)

            for it in range(1, cb.itmax):
                u_curr = np.load(
                    osp.join(abs_work, filename + "_it%d.npy" % (it)))
                u_next = np.load(
                    osp.join(abs_work, filename + "_it%d.npy" % (it + 1)))

                for j in range(1, len(uu) - 1):
                    X = np.block([[X], add_block(u_curr, cb.line_x, j)])
                    y = np.block([[y], [u_next[j]]])

    X = np.delete(X, 0, axis=0)
    y = np.delete(y, 0, axis=0)

    return X, y
Esempio n. 2
0
def forward_multiNN_solver(nn_obj, cb=cb):
    plt.figure()
    p = min(np.random.choice(pi_line), np.random.choice(pi_line))
    
#    u = cb.init_u(p, cpx=2)
    u = harm.complex_init_sin(cb.line_x, 1, pi_line, cb.L)
    
    _, abs_work = LW_solver(u, cb.itmax, "u_test", write=True)
    print (abs_work)
    fetch_real_u = lambda it : np.load(osp.join(abs_work, "u_test_it%d.npy"%(it)))
    
    u_nNext = []
    
    for it in range(1, cb.itmax) :
        if it > 1 :
            u = u_nNext
            u_nNext = []
            
        xs = np.array(u)
        
        xs = nn_obj.scale_inputs(xs)
        xs = xs.reshape(1, -1)

        u_nNext.append(nn_obj.predict(u))
        # u_nNext.shape = 30 
        # use of list type to insert in a second time boundary condition
        
        if it % 5 == 0 :
            plt.clf()        
            plt.plot(cb.line_x, fetch_real_u(it+1), label="True it = %d" %(it+1), c='k')
            plt.plot(cb.line_x, u_nNext, label="Predicted at it = %d" %(it), marker='o', fillstyle = 'none', linestyle= 'none', c=nn_obj.kwargs["color"])
            plt.legend()
            plt.pause(2)
Esempio n. 3
0
    def init_fields(self, phase=0, kc=1, plot=False):

        if self.type_init == "random":
            U_intervals = np.linspace(-self.U, self.U, 10000)
            H_intervals = np.linspace(-self.H, self.H, 10000)

            u_init_field, h_init_field = [], []

            for i in range(1, self.Nx - 1):
                u_init_field.append(np.random.choice(U_intervals))
                h_init_field.append(np.random.choice(H_intervals))

            u_init_field.insert(0, 0.)
            h_init_field.insert(0, 0.)

            u_init_field.insert(len(u_init_field), 0.0)
            h_init_field.insert(len(u_init_field), 0.0)

        if self.type_init == "sin":
            u_init_field = self.U * np.sin(2 * np.pi * self.line_x / self.L +
                                           phase)
            h_init_field = self.H * np.sin(2 * np.pi * self.line_x / self.L +
                                           phase)

        if self.type_init == "choc":
            u_init_field, h_init_field = [], []

            for x in self.line_x:
                if 0.5 < x < self.L / 2. + 0.5:
                    u_init_field.append(self.U)
                    h_init_field.append(self.H)

                else:
                    u_init_field.append(0.)
                    h_init_field.append(0.)

        if self.type_init == 'complex':
            inter_deph = np.linspace(-np.pi, np.pi, 10000)
            u_init_field = harm.complex_init_sin(self.line_x,
                                                 kc,
                                                 inter_deph,
                                                 self.L,
                                                 A=25)
            h_init_field = self.H / self.U * u_init_field

        if plot:
            plt.figure()
            plt.plot(self.line_x, u_init_field, label="u init", color='blue')
            plt.plot(self.line_x,
                     h_init_field,
                     label="h init",
                     color='red',
                     linestyle='--')
            plt.legend(loc='best')

        self.u_init_field = np.array(u_init_field)
        self.h_init_field = np.array(h_init_field)
def xs_multiNN_solver(nn_obj, cb=cb):
    plt.figure()
    p = min(np.random.choice(pi_line), np.random.choice(pi_line))

    #    u = cb.init_u(p, cpx=2)
    u = harm.complex_init_sin(cb.line_x, 1, pi_line, cb.L)

    _, abs_work = LW_solver(u, cb.itmax, "u_test", write=True)
    print(abs_work)

    fetch_real_u = lambda it: np.load(
        osp.join(abs_work, "u_test_it%d.npy" % (it)))

    u_nNext = []

    for it in range(1, cb.itmax):
        if it > 1:
            u = u_nNext
            u_nNext = []

        for j in range(1, cb.Nx - 1):
            xs = np.array(add_block(u, cb.line_x, j))

            if nn_obj.scaler_name != "None":
                #                print ("Before : \n{}".format(xs))
                xs = nn_obj.scale_inputs(xs)
#                print ("After : \n{}".format(xs))
#
#                time.sleep(2)

            xs = xs.reshape(1, -1)

            u_nNext.append(nn_obj.predict(xs)[0, 0])
        # u_nNext.shape = 30
        # use of list type to insert in a second time boundary condition

        u_nNext.insert(0, u[-2])
        u_nNext.insert(len(u), u[1])

        u_nNext = np.array(u_nNext)

        if it % 5 == 0:
            plt.clf()
            plt.plot(cb.line_x[1:cb.Nx - 1],
                     fetch_real_u(it + 1)[1:cb.Nx - 1],
                     label="True it = %d" % (it + 1),
                     c='k')
            plt.plot(cb.line_x[1:cb.Nx - 1],
                     u_nNext[1:cb.Nx - 1],
                     label="Predicted at it = %d" % (it),
                     marker='o',
                     fillstyle='none',
                     linestyle='none',
                     c=nn_obj.kwargs["color"])
            plt.legend()
            plt.pause(2)
Esempio n. 5
0
def create_init(tc ,phase,  kc=1, plot=False): 
    if tc.type_init == "random" :
        U_intervals = np.linspace(-tc.U, tc.U, 10000)
        H_intervals = np.linspace(-tc.H, tc.H, 10000)
    
        u_init_field, h_init_field = [], []
    
        for i in range(1, tc.Nx-1): 
            u_init_field.append(np.random.choice(U_intervals))
            h_init_field.append(np.random.choice(H_intervals))
        
        u_init_field.insert(0, 0.)
        h_init_field.insert(0, 0.)
        
        u_init_field.insert(len(u_init_field), 0.0)
        h_init_field.insert(len(u_init_field), 0.0)

    if tc.type_init == "sin" :
        u_init_field = tc.U*np.sin(2*np.pi*tc.line_x/tc.L + phase)
        h_init_field = tc.H*np.sin(2*np.pi*tc.line_x/tc.L + phase)
    
    if tc.type_init == "choc" :
        u_init_field, h_init_field = [], []
        
        for x in tc.line_x :
            if 0.5 < x < tc.L/2. + 0.5 :
                u_init_field.append(tc.U)
                h_init_field.append(tc.H)
                
            else :
                u_init_field.append(0.)
                h_init_field.append(0.)
    
    if tc.type_init == 'complex'  :
        inter_deph = np.linspace(-np.pi, np.pi, 10000)
        u_init_field = harm.complex_init_sin(tc.line_x, kc, inter_deph, tc.L, A=25)
        h_init_field = tc.H / tc.U * u_init_field
        
    if plot :
        plt.figure()
        plt.plot(tc.line_x, u_init_field, label="u init", color='blue')
        plt.plot(tc.line_x, h_init_field, label="h init", color='red', linestyle='--')
        plt.legend(loc='best')
    
    return u_init_field, h_init_field
Esempio n. 6
0
def Der_multiNN_solver(nn_obj, cb=cb):
    plt.figure()
    p = min(np.random.choice(pi_line), np.random.choice(pi_line))

    #    u = cb.init_u(p, cpx=2)
    u = harm.complex_init_sin(cb.line_x, 1, pi_line, cb.L)

    _, abs_work = LW_solver(u, cb.itmax, "u_test", write=True)
    print(abs_work)
    fetch_real_u = lambda it: np.load(
        osp.join(abs_work, "u_test_it%d.npy" % (it)))

    u_nNext = []
    inf_errs = []

    ax, axx = [], []

    ax1 = plt.subplot(221)  # Erreur a l'iteration n
    ax2 = plt.subplot(222)  # Evolution de la norme infinie de l'erreur
    ax3 = plt.subplot(212)  # Evolution de la prédiction

    ax.append(ax1)
    ax.append(ax2)
    ax.append(ax3)
    axx.append(ax1)
    axx.append(ax3)

    for it in range(1, cb.itmax):
        if it > 1:
            u = u_nNext
            u_nNext = []

        for j in range(1, cb.Nx - 1):
            xs = np.array([
                u[j - 1], u[j], u[j + 1], (u[j + 1] - u[j - 1]) / (2 * cb.dx)
            ])

            xs = nn_obj.scale_inputs(xs)
            xs = xs.reshape(1, -1)

            u_nNext.append(nn_obj.predict(xs)[0, 0])
        # u_nNext.shape = 30
        # use of list type to insert in a second time boundary condition

        u_nNext.insert(0, u[-2])
        u_nNext.insert(len(u), u[1])

        u_nNext = np.array(u_nNext)
        u_nNext_ex = fetch_real_u(it + 1)

        errs = np.array([(u_nNext[i] - u_nNext_ex[i]) for i in range(cb.Nx)])

        inf_err = np.linalg.norm(errs, np.inf)

        inf_errs.append(inf_err)

        if it % 5 == 0:
            axx[0] = ax[0]
            axx[1] = ax[-1]

            for a in axx:
                a.cla()

            # Erreur a l'iteration n
            ax[0].plot(cb.line_x,
                       np.abs(errs),
                       label="Relative Erreur $\hat{u}^{n+1} - u^{n+1}_t$",
                       c=nn_obj.kwargs["color"])

            # Evolution de la norme infinie de l'erreur
            ax[1].scatter(it, inf_err, c=nn_obj.kwargs["color"], s=12)

            ax[-1].plot(cb.line_x[1:cb.Nx - 1],
                        u_nNext_ex[1:cb.Nx - 1],
                        label="True it = %d" % (it + 1),
                        c='k')
            ax[-1].plot(cb.line_x[1:cb.Nx - 1],
                        u_nNext[1:cb.Nx - 1],
                        label="Predicted at it = %d" % (it),
                        marker='o',
                        fillstyle='none',
                        linestyle='none',
                        c=nn_obj.kwargs["color"])

            for a in ax:
                a.legend(prop={'size': 8})

            fig = plt.gcf()
            fig.tight_layout()

            plt.title("Iteration %d" % it)

            plt.pause(2)

    return inf_errs
Esempio n. 7
0
def Der_bootstrap_solver(boot_obj, rescale, cb=cb):
    plt.figure()
    p = min(np.random.choice(pi_line), np.random.choice(pi_line))

    u = harm.complex_init_sin(cb.line_x, 1, pi_line, cb.L)

    _, abs_work = LW_solver(u, cb.itmax, "u_test", write=True)
    print(abs_work)

    fetch_real_u = lambda it: np.load(
        osp.join(abs_work, "u_test_it%d.npy" % (it)))

    u_nNext = []
    var = []

    colors = np.array(
        [mpl.colors.to_rgb(cc) for cc in boot_obj.colors_dict.values()])
    color = np.mean(colors, axis=0)

    inf_errs = []

    ax, axx = [], []

    ax1 = plt.subplot(221)  # Erreur a l'iteration n
    ax2 = plt.subplot(222)  # Evolution de la norme infinie de l'erreur
    ax3 = plt.subplot(212)  # Evolution de la prédiction

    ax.append(ax1)
    ax.append(ax2)
    ax.append(ax3)
    axx.append(ax1)
    axx.append(ax3)

    for it in range(1, cb.itmax):
        if it > 1:
            u = u_nNext
            u_nNext = []
            var = []

        for j in range(1, cb.Nx - 1):
            xs = np.array([
                u[j - 1], u[j], u[j + 1], (u[j + 1] - u[j - 1]) / (2 * cb.dx)
            ])

            mean_curr_pred = boot_obj.bootstrap_prediction(xs,
                                                           rescale=rescale,
                                                           variance=False)

            var_curr_pred = boot_obj.bootstrap_variance(xs, rescale=rescale)

            u_nNext.append(mean_curr_pred)
            var.append(var_curr_pred)

        # u_nNext.shape = 30
        # use of list type to insert in a second time boundary condition

        u_nNext.insert(0, u[-2])
        u_nNext.insert(len(u), u[1])

        u_nNext = np.array(u_nNext)
        u_nNext_ex = fetch_real_u(it + 1)

        errs = np.array([(u_nNext[i] - u_nNext_ex[i]) for i in range(cb.Nx)])

        inf_err = np.linalg.norm(errs, np.inf)
        inf_errs.append(inf_err)

        if it % 5 == 0:
            axx[0] = ax[0]
            axx[1] = ax[-1]

            for a in axx:
                a.cla()

            # Erreur a l'iteration n
            ax[0].plot(cb.line_x,
                       np.abs(errs),
                       label="Abs error : $\hat{u}^{n+1} - u^{n+1}_t$",
                       c=color)

            # Evolution de la norme infinie de l'erreur
            ax[1].scatter(it, inf_err, c=color, s=12)

            ax[-1].plot(cb.line_x[1:cb.Nx - 1],
                        u_nNext_ex[1:cb.Nx - 1],
                        label="True it = %d" % (it + 1),
                        c='k')
            ax[-1].plot(cb.line_x[1:cb.Nx - 1],
                        u_nNext[1:cb.Nx - 1],
                        label="Predicted at it = %d" % (it),
                        marker='o',
                        fillstyle='none',
                        linestyle='none',
                        c=color)

            ax[-1].fill_between(cb.line_x[1:cb.Nx - 1],
                                -10 * np.array(var),
                                10 * np.array(var),
                                facecolor="0.2",
                                alpha=0.4,
                                interpolate=True,
                                label="$\pm \sigma$")

            for a in ax:
                a.legend(prop={'size': 8})

            fig = plt.gcf()
            fig.tight_layout()

            plt.title("Iteration %d" % it)

            plt.pause(2)

    return inf_errs
Esempio n. 8
0
def MHD_NN_solver(nn_obj, tc=tc):
    p = min(np.random.choice(inter_deph), np.random.choice(inter_deph))
    
#    u = cb.init_u(p, cpx=2)
    u = harm.complex_init_sin(tc.line_x, 1, inter_deph, tc.L)
    
    filename = [osp.join(curr_work, "u", "test"), osp.join(curr_work, "h", "test")]
        
    for i, (s,k) in enumerate(zip(filename, ["u","h"])) :
        filename[i] = osp.join(s, "%s_test" % k)
        if osp.exists(s) == False :
            os.mkdir(s)
        
    phase = np.random.choice(inter_deph)
        
    u, h  = create_init(tc, phase, kc=1, plot=False)
    solve_case(tc, u, h, filename)
    
    print ("filename = % s" % filename)
    
    u_test_dir = osp.join(curr_work, "u", "test")
    h_test_dir = osp.join(curr_work, "h", "test")
    
    
    fetch_fields = [ lambda it : np.load(osp.join(f, "%s_test_it%d.npy"%(k, it))) for f,k in zip([u_test_dir, h_test_dir], ["u", "h"])]
    
    fig, axes = plt.subplots(1, 2, figsize=(9,9), num="Evolution u et h -- Prediction")
    
    for it in range(1, tc.itmax) :
        if it > 1 :
            u = u_nNext
            h = h_nNext
            
        u_nNext = []
        h_nNext = []
            
        for j in range(1, tc.Nx-1) :
            xs = np.array(add_block(u, h, j))
            
            xs = nn_obj.scale_inputs(xs)
            xs = xs.reshape(1, -1)

            u_nNext.append(nn_obj.predict(xs)[0,0])
        # u_nNext.shape = 30 
        # use of list type to insert in a second time boundary condition
        
        u_nNext.insert(0, u[-2])
        u_nNext.insert(len(u), u[1])
        
        h_nNext.insert(0, h[-2])
        u_nNext.insert(len(h), h[1])
        
        u_nNext = np.array(u_nNext)
        h_nNext = np.array(h_nNext)
        
        plt.clf()   
        color = iter(["navy", "darkred"])
        
        for n, (ax, k, MLfield) in enumerate(zip(axes, ["u", "h"], [u_nNext, h_nNext])):
            c = next(color)    
            ax.plot(tc.line_x[1:tc.Nx-1], fetch_fields[n](it+1)[1:tc.Nx-1], label="True %s it = %d" %(k, it+1), c='k')
            ax.plot(tc.line_x[1:tc.Nx-1], MLfield[1:tc.Nx-1], label="Predicted %s at it = %d" %(k, it), marker='o', fillstyle = 'none', linestyle= 'none', c=c)
            ax.legend(loc="best")
        
        plt.pause(2)
def Der_bootstrap_solver(boot_obj, rescale, cb=cb):
    plt.figure()
    p = min(np.random.choice(pi_line), np.random.choice(pi_line))

    u = harm.complex_init_sin(cb.line_x, 1, pi_line, cb.L)

    _, abs_work = LW_solver(u, cb.itmax, "u_test", write=True)
    print(abs_work)

    fetch_real_u = lambda it: np.load(
        osp.join(abs_work, "u_test_it%d.npy" % (it)))

    u_nNext = []
    var = []

    for it in range(1, cb.itmax):
        if it > 1:
            u = u_nNext
            u_nNext = []
            var = []

        for j in range(1, cb.Nx - 1):
            xs = np.array([
                u[j - 1], u[j], u[j + 1], (u[j + 1] - u[j - 1]) / (2 * cb.dx)
            ])

            mean_curr_pred = boot_obj.bootstrap_prediction(xs,
                                                           rescale=rescale,
                                                           variance=False)

            var_curr_pred = boot_obj.bootstrap_variance(xs, rescale=rescale)

            u_nNext.append(mean_curr_pred)
            var.append(var_curr_pred)
        # u_nNext.shape = 30
        # use of list type to insert in a second time boundary condition

        u_nNext.insert(0, u[-2])
        u_nNext.insert(len(u), u[1])

        u_nNext = np.array(u_nNext)

        if it % 5 == 0:
            plt.clf()
            plt.plot(cb.line_x[1:cb.Nx - 1],
                     fetch_real_u(it + 1)[1:cb.Nx - 1],
                     label="True it = %d" % (it + 1),
                     c='k')
            plt.plot(cb.line_x[1:cb.Nx - 1],
                     u_nNext[1:cb.Nx - 1],
                     label="Predicted at it = %d" % (it),
                     marker='o',
                     fillstyle='none',
                     linestyle='none',
                     c="red")
            plt.fill_between(cb.line_x[1:cb.Nx - 1],
                             -var,
                             var,
                             facecolor="0.2",
                             alpha=0.4,
                             interpolate=True,
                             label="$\pm \sigma$")
            plt.legend()
            plt.pause(2)