def __getattr__(self, attr):  # only called if not in wrapper dict
        r"""
        Get a member of this object. If the member is not found in this object, the wrapped object will be queried.

        Parameters:
            attr (string): Name of the attribute/member to retrieve

        Returns:
            member: attribute or member of the wrapper or the wrapped object by that preference.
        """
        return getattr(self.obj, attr)

if __name__ == '__main__':
    bridge = LEProblem(bridge2Dstochastic())
    tau_adapter = tauadaptor(bridge.get_tau())
    mesh_adapter = meshadaptor(mesh_0=bridge.mesh, CVaR=bridge.CVaR)

    bridge.sample(0)


    for i in range(20):
        monte_carlo_solve(bridge)
        bridge.tau.vector()[:] = tau_adapter.nextTau(bridge.get_e_n())
        bridge.new_adaptGamma()

    plt.figure()
    plot(bridge.mesh)
    plt.show()
    plt.figure()
    plot(bridge.phi_next[0])
    plt.show()
Beispiel #2
0
def run_LSTM_optimization(
        model_path='Neural_Networks/LSTM/model/ConvLSTM-model_3_9_9_9_9_1_sequence_5in_10out_3618Samples_77batch_100epochs.pth',
        random_state=0):
    converge = False
    LEP = LEProblem(bridge2Dstochastic())
    if random_state > 0:
        get_random_g(LEP, random_state)
    tau_adapter = tauadaptor(LEP.get_tau())
    mesh_adapter = meshadaptor(mesh_0=LEP.mesh, CVaR=LEP.CVaR)
    model = EncoderDecoderPhiLSTM(nf=9, in_chan=3)

    model.load_state_dict(torch.load(model_path))

    IterationStep = 0
    get_new_tensor_iter = -75
    plot_count = 0
    iters = []
    conv_min_iter = 50

    taus = []
    taus.append(LEP.tau_0)
    gammas = []
    es = []
    controls = []
    Js = []
    mesh_count = 1

    tic()

    k = 0
    times = []
    V = FunctionSpace(targetmesh, VectorElement("CG", targetmesh.ufl_cell(),
                                                1))
    F = FunctionSpace(
        targetmesh,
        MixedElement([
            FiniteElement(t, targetmesh.ufl_cell(), d)
            for t, d in [("CG", 1), ("R", 0)]
        ]))

    phi_val = []
    ux_val = []
    uy_val = []
    while not converge:
        StartTime = tm.time()
        IterationStep += 1
        get_new_tensor_iter += 1
        plot_count += 1
        iters.append(IterationStep)
        print("\nIter: {IterationStep}".format(IterationStep=IterationStep))

        # solving
        SE = LEP.SE(LEP.u, LEP.phi_n[0], LEP.v_u, LEP.g)
        solve(lhs(SE) == rhs(SE),
              LEP.u_n,
              bcs=LEP.bcSE,
              solver_parameters={
                  "linear_solver": "umfpack",
                  "preconditioner": "default"
              },
              form_compiler_parameters=None)

        if get_new_tensor_iter >= 50 and mesh_count < 2:
            u_n = interpolateLG(LEP.u_n, V)
            phi_n = interpolateLG(LEP.phi_n, F)
            phi_val.append(phi_n.vector()[:])
            ux, uy = u_n.split(deepcopy=True)
            ux_val.append(ux.vector()[:])
            uy_val.append(uy.vector()[:])

            phi_val = phi_val[-5:]
            ux_val = ux_val[-5:]
            uy_val = uy_val[-5:]

        # get u_k and phi_{k-1}
        if get_new_tensor_iter >= 55 and mesh_count < 2:
            deterministic_LSTM_solve(LEP, phi_val, ux_val, uy_val, model)

            get_new_tensor_iter = 0

        # solve adjoint equation

        LEP.p_n.assign(LEP.u_n)  # p_n = u_n

        # solve gradient equation
        GE = LEP.GE(LEP.phi, LEP.phi_n, LEP.v_phi, LEP.p_n, LEP.u_n,
                    LEP.tau[0], LEP.gamma)
        solve(lhs(GE) == rhs(GE),
              LEP.phi_next,
              bcs=None,
              solver_parameters={
                  "linear_solver": "umfpack",
                  "preconditioner": "default"
              },
              form_compiler_parameters=None)

        LEP.project_phi()

        # optimization adaptions
        tau_n = LEP.get_tau()
        taus.append(tau_n)

        e_n = LEP.get_e_n()
        es.append(e_n)

        control = LEP.get_control_change()
        controls.append(control / tau_n)

        gammas.append(LEP.gamma(0))

        J = assemble(LEP.J(LEP.u_n, LEP.phi_next[0], LEP.gamma))

        Js.append(J)

        LEP.tau.vector()[:] = tau_adapter.nextTau(e_n)[0]

        LEP.new_adaptGamma()

        if plot_count >= 100:
            plot(LEP.phi_n[0])
            plt.show()
            plot_count = 0

        NewMeshIndicator, new_mesh = mesh_adapter.update(
            LEP.phi_next, LEP.u_n, controls[-1], LEP.mesh)
        conv_min_iter += 1
        if NewMeshIndicator:
            mesh_count += 1
            conv_min_iter = 0
            LEP.updateMesh(new_mesh)
            control = 1000
        LEP.phi_last.assign(LEP.phi_n)
        LEP.phi_n.assign(LEP.phi_next)
        k += 1

        if control < 1 and conv_min_iter >= 50 and mesh_count >= 4:  # Kovergenz
            converge = True
            print('convert after:' + str(k) + 'steps')
        if k == 700:
            converge = True
            print('reach may itteration steps')
        EndTime = tm.time()
        times.append(EndTime - StartTime)
    tac()
Beispiel #3
0
if LEP.stochastic and LEP.CVaR:
    tau_adapter = tauadaptor(
        tau_0=LEP.get_tau_stoch(),
        TOL=1e-1,
        TOL_t=50,
        tau_max=1e-5,
        tau_min=1e-12,
        tau_t_max=1e1,
        tau_t_min=1e-12
    )  #, TOL=1e-1, TOL_t=1e2, tau_max=1e-5, tau_min=1e-12, tau_t_max=1e0, tau_t_min=1e-12
else:
    tau_adapter = tauadaptor(LEP.get_tau())

mesh_adapter = meshadaptor(mesh_0=LEP.mesh,
                           CVaR=LEP.CVaR,
                           verticesMultiplicator=1.2,
                           theta=0.4,
                           control=1)

# Neural Network imports
global targetmesh
targetmesh = RectangleMesh(Point(-1.0, 0.0), Point(1.0, 1.0), 200, 100,
                           "right/left")

import sys
import torch
from Neural_Networks.CNN.CNN_classes import phiDeepCNN
from torch.nn.utils.rnn import pad_sequence

model = phiDeepCNN(3, 15)
model.load_state_dict(
Beispiel #4
0
mc_problem = None

LEP = LEProblem(bridge2D())

if LEP.stochastic and LEP.CVaR:
    tau_adapter = tauadaptor(tau_0=LEP.get_tau_stoch(),
                             TOL=1e-1,
                             TOL_t=50,
                             tau_max=1e-5,
                             tau_min=1e-12,
                             tau_t_max=1e1,
                             tau_t_min=1e-12)
else:
    tau_adapter = tauadaptor(LEP.get_tau())

mesh_adapter = meshadaptor(mesh_0=LEP.mesh, CVaR=LEP.CVaR)


def tic():
    global _start_time
    _start_time = tm.time()


def tac():
    t_sec = round(tm.time() - _start_time)
    (t_min, t_sec) = divmod(t_sec, 60)
    (t_hour, t_min) = divmod(t_min, 60)
    print('Time passed: {}hour:{}min:{}sec'.format(t_hour, t_min, t_sec))


def LSTM_gradienten_step(LEP, phi_val, ux_val, uy_val, model):
Beispiel #5
0
def run_CNN_optimization(
        LEP,
        model_path='Neural_Networks/CNN/model/CNN-model_3_15_15_15_15_15_1_one_step_77_Batch_100_epoch.pth',
        random_state=0):
    converge = False

    tau_adapter = tauadaptor(LEP.get_tau())
    mesh_adapter = meshadaptor(mesh_0=LEP.mesh, CVaR=LEP.CVaR)

    model = phiDeepCNN(3, 15)
    model.load_state_dict(torch.load(model_path))

    IterationStep = 0
    get_new_tensor_iter = -24
    plot_count = 0
    iters = []
    conv_min_iter = 50
    times = []
    taus = []
    taus.append(LEP.tau_0)
    gammas = []
    es = []
    controls = []
    Js = []
    mesh_count = 1

    tic()
    k = 0
    while not converge:
        StartTime = tm.time()
        IterationStep += 1
        get_new_tensor_iter += 1
        plot_count += 1
        iters.append(IterationStep)
        print("\nIter: {IterationStep}".format(IterationStep=IterationStep))

        # solving
        SE = LEP.SE(LEP.u, LEP.phi_n[0], LEP.v_u, LEP.g)
        solve(lhs(SE) == rhs(SE),
              LEP.u_n,
              bcs=LEP.bcSE,
              solver_parameters={
                  "linear_solver": "umfpack",
                  "preconditioner": "default"
              },
              form_compiler_parameters=None)

        # get u_k and phi_{k-1}
        if get_new_tensor_iter >= 55 and mesh_count < 2:
            deterministic_NN_solve(LEP, model)
            get_new_tensor_iter = 0

        # solve adjoint equation

        LEP.p_n.assign(LEP.u_n)  # p_n = u_n

        # solve gradient equation
        GE = LEP.GE(LEP.phi, LEP.phi_n, LEP.v_phi, LEP.p_n, LEP.u_n,
                    LEP.tau[0], LEP.gamma)
        solve(lhs(GE) == rhs(GE),
              LEP.phi_next,
              bcs=None,
              solver_parameters={
                  "linear_solver": "umfpack",
                  "preconditioner": "default"
              },
              form_compiler_parameters=None)

        LEP.project_phi()

        # optimization adaptions
        tau_n = LEP.get_tau()
        taus.append(tau_n)

        e_n = LEP.get_e_n()
        es.append(e_n)

        control = LEP.get_control_change()
        controls.append(control / tau_n)

        gammas.append(LEP.gamma(0))

        J = assemble(LEP.J(LEP.u_n, LEP.phi_next[0], LEP.gamma))

        Js.append(J)

        LEP.tau.vector()[:] = tau_adapter.nextTau(e_n)[0]

        LEP.new_adaptGamma()

        if plot_count >= 100:
            plot(LEP.phi_n[0])
            plt.show()
            plot_count = 0

        NewMeshIndicator, new_mesh = mesh_adapter.update(
            LEP.phi_next, LEP.u_n, controls[-1], LEP.mesh)
        conv_min_iter += 1
        if NewMeshIndicator:
            mesh_count += 1
            conv_min_iter = 0
            LEP.updateMesh(new_mesh)
            control = 1000
        LEP.phi_last.assign(LEP.phi_n)
        LEP.phi_n.assign(LEP.phi_next)
        k += 1
        EndTime = tm.time()
        times.append(EndTime - StartTime)

        if control < 1 and conv_min_iter >= 50 and mesh_count >= 4:  # Kovergenz
            converge = True
            tac()
            print("J=", Js[-1])
            print("complince:", compliance(LEP))

            # plot metriks
            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
            ax1.plot(iters, taus[1:])
            ax1.set_title("τ per iteration")
            ax3.plot(iters, gammas)
            ax3.set_title("γ per iteration")
            ax2.plot(iters, times)
            ax2.set_title("computing time per iteration")
            ax4.plot(iters, Js)
            ax4.set_title("J^eps(φ) per iteration")
            plt.show()

    return Js