Пример #1
0
 def __init__(self, batch_size, resolution):
     self.resolution = resolution
     self.V = get_space(resolution)
     self.dofs = len(self.V.dofmap().dofs())
     self.phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
     self.batch_size = batch_size
     self.solver = Fin(self.V)
Пример #2
0
    def __init__(self, resolution=40, out_type="total_avg"):
        """ 
        INPUTS:
     
        """
        V = get_space(resolution)
        dofs = len(V.dofmap().dofs())
        self.solver = Fin(V)
        self.phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
        self.phi = self.phi[:, 0:10]
        self.model = load_parametric_model('relu', Adam, 0.004, 6, 50, 150,
                                           600)

        self.out_type = out_type

        if out_type == "total_avg":
            out_dim = 1
        elif out_type == "subfin_avg":
            out_dim = 5
        elif out_type == "rand_pt":
            out_dim = 1
        elif out_type == "rand_pts":
            out_dim = 5

        mm.PyModPiece.__init__(self, [5], [out_dim])
Пример #3
0
class FOM_forward(mm.PyModPiece):
    """
    Solves the thermal fin steady state problem with
    a full order model
    """
    def __init__(self, resolution=40, out_type="total_avg"):
        """ 
        INPUTS:
     
        """
        V = get_space(resolution)
        dofs = len(V.dofmap().dofs())
        self.solver = Fin(V)
        self.out_type = out_type

        if out_type == "total_avg":
            out_dim = 1
        elif out_type == "subfin_avg":
            out_dim = 5
        elif out_type == "rand_pt":
            out_dim = 1
        elif out_type == "rand_pts":
            out_dim = 5
        mm.PyModPiece.__init__(self, [5], [out_dim])

    def EvaluateImpl(self, inputs):
        """
        Performs the forward solve and returns observations.
        
        """
        z = inputs[0]

        x, y, A, B, C = self.solver.forward_five_param(z)
        output = self.solver.qoi_operator(x)
        self.outputs = [output]
Пример #4
0
def generate(dataset_size, resolution=40):
    '''
    Create a tensorflow dataset where the features are thermal conductivity parameters
    and the labels are the differences in the quantity of interest between the high 
    fidelity model and the reduced order model (this is the ROM error)

    Arguments: 
        dataset_size - number of feature-label pairs
        resolution   - finite element mesh resolution for the high fidelity model

    Returns:
        dataset      - Tensorflow dataset created from tensor slices
    '''

    V = get_space(resolution)
    dofs = len(V.dofmap().dofs())

    # TODO: Improve this by using mass matrix covariance. Bayesian prior may work well too
    z_s = np.random.uniform(0.1, 1, (dataset_size, dofs))
    phi = np.loadtxt('data/basis.txt', delimiter=",")
    solver = Fin(V)
    errors = np.zeros((dataset_size, 1))

    m = Function(V)
    for i in range(dataset_size):
        m.vector().set_local(z_s[i, :])
        w, y, A, B, C = solver.forward(m)
        psi = np.dot(A, phi)
        A_r, B_r, C_r, x_r, y_r = solver.reduced_forward(A, B, C, psi, phi)
        errors[i][0] = y - y_r

    dataset = tf.data.Dataset.from_tensor_slices((z_s, errors))

    return dataset
Пример #5
0
class DL_ROM_forward(mm.PyModPiece):
    """
    Solves the thermal fin steady state problem with 
    projection based ROM with a given basis and augments
    QoI prediction with deep learning prediciton.
    """
    def __init__(self, resolution=40, out_type="total_avg"):
        """ 
        INPUTS:
     
        """
        V = get_space(resolution)
        dofs = len(V.dofmap().dofs())
        self.solver = Fin(V)
        self.phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
        self.phi = self.phi[:, 0:10]
        self.model = load_parametric_model('relu', Adam, 0.004, 6, 50, 150,
                                           600)

        self.out_type = out_type

        if out_type == "total_avg":
            out_dim = 1
        elif out_type == "subfin_avg":
            out_dim = 5
        elif out_type == "rand_pt":
            out_dim = 1
        elif out_type == "rand_pts":
            out_dim = 5

        mm.PyModPiece.__init__(self, [5], [out_dim])

    def EvaluateImpl(self, inputs):
        """
        Performs the forward solve and returns observations.
        
        """
        z = inputs[0]
        A_r, B_r, C_r, x_r, y_r = self.solver.r_fwd_no_full_5_param(
            z, self.phi)
        e_NN = self.model.predict(z.reshape((1, 5)))

        if self.out_type == "total_avg":
            output = np.array([y_r + e_NN[0, 0]])
        else:
            # The QoI operator determines whether we look at subfin averages
            # or random points on the boundary or domain
            output = self.solver.reduced_qoi_operator(x_r) + e_NN[0]

        self.outputs = [output]
Пример #6
0
class FinInput:
    '''
    A class to create a thermal fin instance with Tensorflow input functions
    '''
    def __init__(self, batch_size, resolution):
        self.resolution = resolution
        self.V = get_space(resolution)
        self.dofs = len(self.V.dofmap().dofs())
        self.phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
        self.batch_size = batch_size
        self.solver = Fin(self.V)

    def train_input_fn(self):
        params = np.random.uniform(0.1, 1, (self.batch_size, self.dofs))
        errors = np.zeros((self.batch_size, 1))

        for i in range(self.batch_size):
            m = Function(self.V)
            m.vector().set_local(params[i, :])
            w, y, A, B, C = self.solver.forward(m)
            psi = np.dot(A, self.phi)
            A_r, B_r, C_r, x_r, y_r = self.solver.reduced_forward(
                A, B, C, psi, self.phi)
            errors[i][0] = y - y_r

        return ({
            'x': tf.convert_to_tensor(params)
        }, tf.convert_to_tensor(errors))

    def eval_input_fn(self):
        params = np.random.uniform(0.1, 1, (self.batch_size, self.dofs))
        errors = np.zeros((self.batch_size, 1))

        for i in range(self.batch_size):
            m = Function(self.V)
            m.vector().set_local(params[i, :])
            w, y, A, B, C = self.solver.forward(m)
            psi = np.dot(A, self.phi)
            A_r, B_r, C_r, x_r, y_r = self.solver.reduced_forward(
                A, B, C, psi, self.phi)
            errors[i][0] = y - y_r

        return ({
            'x': tf.convert_to_tensor(params)
        }, tf.convert_to_tensor(errors))
Пример #7
0
def generate_and_save_dataset(dataset_size, resolution=40):
    V = get_space(resolution)
    dofs = len(V.dofmap().dofs())
    z_s = np.random.uniform(0.1, 1, (dataset_size, dofs))
    phi = np.loadtxt('data/basis.txt', delimiter=",")
    solver = Fin(V)
    errors = np.zeros((dataset_size, 1))

    m = Function(V)
    for i in range(dataset_size):
        m.vector().set_local(z_s[i, :])
        w, y, A, B, C = solver.forward(m)
        psi = np.dot(A, phi)
        A_r, B_r, C_r, x_r, y_r = solver.reduced_forward(A, B, C, psi, phi)
        errors[i][0] = y - y_r

    np.savetxt('data/z_s_train.txt', z_s, delimiter=",")
    np.savetxt('data/errors_train.txt', errors, delimiter=",")
Пример #8
0
    def __init__(self, resolution=40, out_type="total_avg"):
        """ 
        INPUTS:
     
        """
        V = get_space(resolution)
        dofs = len(V.dofmap().dofs())
        self.solver = Fin(V)
        self.out_type = out_type

        if out_type == "total_avg":
            out_dim = 1
        elif out_type == "subfin_avg":
            out_dim = 5
        elif out_type == "rand_pt":
            out_dim = 1
        elif out_type == "rand_pts":
            out_dim = 5
        mm.PyModPiece.__init__(self, [5], [out_dim])
Пример #9
0
def generate_five_param_np(dataset_size, resolution=40):
    V = get_space(resolution)
    z_s = np.random.uniform(0.1, 1, (dataset_size, 5))
    phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
    phi = phi[:, 0:10]
    solver = Fin(V)
    errors = np.zeros((dataset_size, 1))
    y_s = np.zeros((dataset_size, 1))
    y_r_s = np.zeros((dataset_size, 1))

    for i in range(dataset_size):
        w, y, A, B, C = solver.forward_five_param(z_s[i, :])
        y_s[i][0] = y
        psi = np.dot(A, phi)
        A_r, B_r, C_r, x_r, y_r = solver.reduced_forward(A, B, C, psi, phi)
        y_r_s[i][0] = y_r
        errors[i][0] = y - y_r

    return (z_s, errors)
Пример #10
0
def generate_five_param(dataset_size, resolution=40):
    V = get_space(resolution)
    dofs = len(V.dofmap().dofs())

    # TODO: Improve this by using mass matrix covariance. Bayesian prior may work well too
    z_s = np.random.uniform(0.1, 1, (dataset_size, 5))
    phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
    phi = phi[:, 0:20]
    solver = Fin(V)
    errors = np.zeros((dataset_size, 1))

    for i in range(dataset_size):
        w, y, A, B, C = solver.forward_five_param(z_s[i, :])
        psi = np.dot(A, phi)
        A_r, B_r, C_r, x_r, y_r = solver.reduced_forward(A, B, C, psi, phi)
        errors[i][0] = y - y_r

    #  np.savetxt('data/z_s_eval.txt', z_s, delimiter=",")
    #  np.savetxt('data/errors_eval.txt', errors, delimiter=",")
    dataset = tf.data.Dataset.from_tensor_slices((z_s, errors))

    return dataset
Пример #11
0
def gen_five_param_subfin_avg(dataset_size, resolution=40):
    V = get_space(resolution)
    z_s = np.random.uniform(0.1, 1, (dataset_size, 5))
    phi = np.loadtxt('data/basis_five_param.txt', delimiter=",")
    phi = phi[:, 0:10]
    solver = Fin(V)
    errors = np.zeros((dataset_size, 5))
    avgs = np.zeros((dataset_size, 5))
    avgs_r = np.zeros((dataset_size, 5))

    for i in range(dataset_size):
        w, y, A, B, C = solver.forward_five_param(z_s[i, :])
        avgs[i] = solver.qoi_operator(w)
        psi = np.dot(A, phi)
        A_r, B_r, C_r, x_r, y_r = solver.reduced_forward(A, B, C, psi, phi)
        avgs_r[i] = solver.reduced_qoi_operator(x_r)
        errors[i] = avgs[i] - avgs_r[i]

    return (z_s, errors)
# Create a fin geometry
geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
        + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
        + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
        + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
        + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
        + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
        + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
        + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
        + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

mesh = generate_mesh(geometry, 40)

V = FunctionSpace(mesh, 'CG', 1)
dofs = len(V.dofmap().dofs())
solver = Fin(V)

##########################################################3
# Basis initialization with dummy solves and POD
##########################################################3
samples = 10
Y = np.zeros((samples, dofs))
for i in range(0, samples):
    k = np.random.uniform(0.1, 1.0, 5)
    w = solver.forward_five_param(k)[0]
    Y[i, :] = w.vector()[:]

K = np.dot(Y, Y.T)

# Initial basis vectors computed using proper orthogonal decomposition
e, v = np.linalg.eig(K)
###############################################################################
#                                  Driver                                     #
###############################################################################
if __name__ == "__main__":

    #=== Set hyperparameters ===#
    hyper_p = HyperParameters()

    #=== Set run options ===#
    run_options = RunOptions(hyper_p)

    #####################################
    #   Form Test Parameters and State  #
    #####################################
    V, _ = get_space(40)
    solver = Fin(V)

    #=== Load observation indices ===#
    print('Loading Boundary Indices')
    df_obs_indices = pd.read_csv(run_options.observation_indices_savefilepath +
                                 '.csv')
    obs_indices = df_obs_indices.to_numpy()

    #=== Load testing data ===#
    if os.path.isfile(run_options.parameter_test_savefilepath + '.csv'):
        print('Loading Test Data')
        df_parameter_test = pd.read_csv(
            run_options.parameter_test_savefilepath + '.csv')
        df_state_obs_test = pd.read_csv(
            run_options.state_obs_test_savefilepath + '.csv')
        parameter_test = df_parameter_test.to_numpy()
Пример #14
0
import sys
sys.path.insert(0,'/home/fenics/Installations/MUQ_INSTALL/lib')
import pymuqModeling as mm # Needed for Gaussian distribution
import pymuqApproximation as ma # Needed for Gaussian processes
import pymuqSamplingAlgorithms as ms # Needed for MCMC

resolution = 40
r_fwd = ROM_forward(resolution, out_type="subfin_avg")
d_fwd = DL_ROM_forward(resolution, out_type="subfin_avg")
f_fwd = FOM_forward(resolution, out_type="subfin_avg")

#z_true = np.random.uniform(0.1,1, (1,5))
z_true = np.array([[0.41126864, 0.61789679, 0.75873243, 0.96527541, 0.22348076]])

V = get_space(resolution)
full_solver = Fin(V)
w, y, A, B, C = full_solver.forward_five_param(z_true[0,:])
qoi = full_solver.qoi_operator(w)
obsData = qoi

def MCMC_sample(fwd):
    # Define prior
    logPriorMu = 0.5*np.ones(5)
    logPriorCov = 0.5*np.eye(5)

    logPrior = mm.Gaussian(logPriorMu, logPriorCov).AsDensity()

    # Likelihood
    noiseVar = 1e-4
    noiseCov = noiseVar*np.eye(obsData.size)
    likelihood = mm.Gaussian(obsData, noiseCov).AsDensity()
Пример #15
0
# Create a fin geometry
geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
        + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
        + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
        + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
        + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
        + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
        + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
        + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
        + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

mesh = generate_mesh(geometry, 40)

V = FunctionSpace(mesh, 'CG', 1)
dofs = len(V.dofmap().dofs())
solver = Fin(V)

##########################################################3
# Basis initialization with dummy solves and POD
##########################################################3
samples = 10
Y = np.zeros((samples, dofs))
for i in range(0, samples):

    if i == 0:
        m = interpolate(
            Expression(
                "0.1 + exp(-(pow(x[0] - 0.5, 2) + pow(x[1], 2)) / 0.01)",
                degree=2), V)
    elif i == 1:
        m = interpolate(Expression("2*x[0] + 0.1", degree=2), V)
Пример #16
0
# Create a fin geometry
geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
        + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
        + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
        + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
        + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
        + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
        + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
        + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
        + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

mesh = generate_mesh(geometry, 40)

V = FunctionSpace(mesh, 'CG', 1)
dofs = len(V.dofmap().dofs())
f = Fin(V)

basis = np.loadtxt('data/basis.txt', delimiter=",")
m = interpolate(Expression("2*x[1] + 1.0", degree=2), V)
w, y, A, B, C = f.forward(m, V)
p = plot(m, title="Conductivity")
plt.colorbar(p)
plt.show()
p = plot(w, title="Temperature")
plt.colorbar(p)
plt.show()
A_r, B_r, C_r, x_r, y_r = f.reduced_forward(A, B, C, np.dot(A, basis), basis)
x_tilde = np.dot(basis, x_r)
x_tilde_f = Function(V)
x_tilde_f.vector().set_local(x_tilde)
p = plot(x_tilde_f, title="Temperature reduced")
Пример #17
0
        + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
        + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
        + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
        + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
        + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
        + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

mesh = generate_mesh(geometry, 40)
plot(mesh)
plt.show()

V = FunctionSpace(mesh, 'CG', 1)
dofs = len(V.dofmap().dofs())
print("DOFS: {}".format(dofs))

# Pick a more interesting conductivity to see what happens
#  m = Function(V)

#  m = interpolate(Expression("2.0*exp(-(pow(x[0] - 0.5, 2) + pow(x[1]-0.5, 2)) / 0.02)", degree=2), V)
m = interpolate(Expression("5- x[1]", degree=2), V)
solver = Fin(V)
w = solver.forward(m)[0]
fig = plt.figure()
p = plot(m, title="Conductivity")
plt.colorbar(p)
plt.show()
plt.figure()
p = plot(w, title="Temperature")
plt.colorbar(p)
plt.show()
# Create a fin geometry
geometry = Rectangle(Point(2.5, 0.0), Point(3.5, 4.0)) \
        + Rectangle(Point(0.0, 0.75), Point(2.5, 1.0)) \
        + Rectangle(Point(0.0, 1.75), Point(2.5, 2.0)) \
        + Rectangle(Point(0.0, 2.75), Point(2.5, 3.0)) \
        + Rectangle(Point(0.0, 3.75), Point(2.5, 4.0)) \
        + Rectangle(Point(3.5, 0.75), Point(6.0, 1.0)) \
        + Rectangle(Point(3.5, 1.75), Point(6.0, 2.0)) \
        + Rectangle(Point(3.5, 2.75), Point(6.0, 3.0)) \
        + Rectangle(Point(3.5, 3.75), Point(6.0, 4.0)) \

mesh = generate_mesh(geometry, 40)

V = FunctionSpace(mesh, 'CG', 1)
dofs = len(V.dofmap().dofs())
f = Fin(V)

basis = np.loadtxt('../data/basis_five_param.txt', delimiter=",")
basis = basis[:, 0:10]
k_s = np.random.uniform(0.1, 1.0, 5)
w, y, A, B, C = f.forward_five_param(k_s)
m = f.five_param_to_function(k_s)
p = plot(m, title="Conductivity")
plt.colorbar(p)
plt.show()
p = plot(w, title="Temperature")
plt.colorbar(p)
plt.show()
A_r, B_r, C_r, x_r, y_r = f.reduced_forward(A, B, C, np.dot(A, basis), basis)
x_tilde = np.dot(basis, x_r)
x_tilde_f = Function(V)