Ejemplo n.º 1
0
    def test_gradientOfFaces(self):
        # Tests that gradients are correctly computed

        print("Testing gradients of faces in triangular mesh")

        # Create mesh
        nodes = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
        triangles = np.array([[0, 1, 2], [0, 2, 3]])
        mesh = mesher.Mesh(triangles, nodes)
        # Get gradient coefficient matrix
        gradAndMat = mesh.gradAndAreaForSimplices(grads=True, areas=True)
        gradMat = gradAndMat["gradMat"]
        areas = gradAndMat["areas"]
        self.assertTrue(np.linalg.norm(areas - np.array([0.5, 0.5])) < 1e-10)

        # Set values at nodes
        V = np.array([0, 0, 0, 1])
        # Compute gradients at triangles
        grad = (gradMat * V).reshape((2, 2))
        # Make sure that the all gradients are correct
        self.assertTrue(np.linalg.norm(grad[0, :] - np.array([0, 0])) < 1e-10)
        self.assertTrue(np.linalg.norm(grad[1, :] - np.array([-1, 1])) < 1e-10)

        # Set values at nodes
        V = np.array([1, 0, 0, 0])
        # Compute gradients at triangles
        grad = (gradMat * V).reshape((2, 2))
        # Make sure that the all gradients are correct
        self.assertTrue(np.linalg.norm(grad[0, :] - np.array([-1, 0])) < 1e-10)
        self.assertTrue(np.linalg.norm(grad[1, :] - np.array([0, -1])) < 1e-10)

        # Set values at nodes
        V = np.array([0, 1, 0, 0])
        # Compute gradients at triangles
        grad = (gradMat * V).reshape((2, 2))
        # Make sure that the all gradients are correct
        self.assertTrue(np.linalg.norm(grad[0, :] - np.array([1, -1])) < 1e-10)
        self.assertTrue(np.linalg.norm(grad[1, :] - np.array([0, 0])) < 1e-10)

        # Set values at nodes
        V = np.array([0, 0, 0, 1])
        # Compute gradients at triangles
        grad = (gradMat * V).reshape((2, 2))
        # Make sure that the all gradients are correct
        self.assertTrue(np.linalg.norm(grad[0, :] - np.array([0, 0])) < 1e-10)
        self.assertTrue(np.linalg.norm(grad[1, :] - np.array([-1, 1])) < 1e-10)

        # Acquire gradients of nodes
        S2N = mesh.S2NByArea(areas)
        gradNodes = S2N * grad
        self.assertTrue(
            np.linalg.norm(gradNodes[0, :] - np.mean(grad, axis=0)) < 1e-10)
        self.assertTrue(np.linalg.norm(gradNodes[1, :] - grad[0, :]) < 1e-10)
        self.assertTrue(
            np.linalg.norm(gradNodes[2, :] - np.mean(grad, axis=0)) < 1e-10)
        self.assertTrue(np.linalg.norm(gradNodes[3, :] - grad[1, :]) < 1e-10)
Ejemplo n.º 2
0
    def test_simplexNeighbors1D(self):
        # Test case to make sure that the neighboring simplices are actually neighboring (in 1D).

        print("Testing acquiring simplex neighbors 1D!")

        # Create 2D mesh
        N = int(2e2)
        nodes = np.linspace(0, 1, num=N, dtype=np.double).reshape((-1, 1))
        triangles = np.array(
            [np.arange(0, N - 1), np.arange(1, N)],
            dtype=np.uintc).transpose().copy()
        triangles = triangles[:, [1, 0]].copy()
        mesh = mesher.Mesh(triangles=triangles, nodes=nodes)
        mesh.getBoundary()

        # Get edges and neighbors
        edges = mesher.Mesh.getEdges(mesh.triangles,
                                     mesh.topD,
                                     mesh.topD,
                                     libInstance=mesh._libInstance)
        neighs = mesher.Mesh.getSimplexNeighbors(edges["simplicesForEdges"],
                                                 edges["edgesForSimplices"],
                                                 libInstance=mesh._libInstance)

        # go through all simplices
        for iterSimp in range(mesh.NT):

            # go through all nodes in current simplex
            for iterNodes in mesh.triangles[iterSimp, :]:
                # Initialize number of found matches
                numMatches = 0

                # Go through all neighboring simplices
                for iterNeighs in neighs[iterSimp, :]:
                    # If current simplex is none due to boundary
                    if iterNeighs == mesh.NT:
                        numMatches = numMatches + 1
                    else:
                        # If current node is part of current neighboring simplex
                        if np.any(mesh.triangles[iterNeighs, :] == iterNodes):
                            numMatches = numMatches + 1

                # Make sure that match was found
                self.assertTrue(numMatches >= 1)
Ejemplo n.º 3
0
# Number of nodes
N = int(2e2)

# Define the Matérn random field
r = 0.55  # Set correlation range (range for which two points have approximately 0.1 correlation)
nu = 1.51  # Set smoothness
sigma = 1  # Set standard deviation
sigmaEps = 1e-2  # Set noise level

# Create 1D mesh
nodes = np.linspace(0 - 1 * r, 1 + 1 * r, num=N, dtype=np.double).reshape(
    (-1, 1))
triangles = np.array(
    [np.arange(0, N - 1), np.arange(1, N)], dtype=np.uintc).transpose().copy()
triangles = triangles[:, [1, 0]].copy()
mesh = mesher.Mesh(triangles=triangles, nodes=nodes)
mesh.getBoundary()

# Create Dirichlet boundary condition
BCDirichlet = np.NaN * np.ones((mesh.N))
BCDirichlet[mesh.getBoundary()["nodes"]] = 0
BCDirichlet = None
# Create Robin boundary condition
BCRobin = np.ones((mesh.boundary["edges"].shape[0], 2))
BCRobin[:, 0] = 0  # Association with constant
BCRobin[:, 1] = -0.3  # Association with function
# BCRobin = None
# Create MaternFEM object
fem = FEM.MaternFEM(mesh=mesh,
                    childParams={'r': r},
                    nu=nu,
Ejemplo n.º 4
0
    def test_meshRefinement(self):
        # Test case refining meshes

        print("Testing refining meshes!")

        # % Create 1D mesh

        nodes = np.linspace(0, 1, 4, dtype=np.float64).reshape((-1, 1))
        triangles = np.stack(
            (np.arange(0, nodes.size - 1),
             np.arange(1, nodes.size))).transpose().astype(np.uintc)
        meshm0 = mesher.Mesh(triangles, nodes)

        # Set maximum diameter for each node
        maxDiamArray = 0.2 * np.ones((meshm0.N))
        maxDiamArray[2] = 0.05
        # Create refined sphere
        meshm1 = meshm0.refine(maxDiam=maxDiamArray, maxNumNodes=meshm0.N + 50)

        # Make sure that the right number of nodes and simplices
        self.assertTrue(meshm1.nodes.shape[0] == 13)
        self.assertTrue(meshm1.triangles.shape[0] == 12)

        # % Create simplest 2D mesh

        # Create Mesh
        mesh0 = mesher.Mesh(
            np.array([[0, 1, 2], [1, 2, 3]], dtype=np.uintc),
            np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float64))

        # Set maximum diameter for each node
        maxDiamArray = 0.8 * np.ones((mesh0.N))
        maxDiamArray[0] = 0.1

        # Create refined sphere
        mesh1 = mesh0.refine(maxDiam=maxDiamArray, maxNumNodes=mesh0.N + 50)

        # Make sure that the right number of nodes and simplices
        self.assertTrue(mesh1.nodes.shape[0] == 21)
        self.assertTrue(mesh1.triangles.shape[0] == 24)

        # % Create spherical mesh

        # Create unrefined sphere
        meshSphere0 = mesher.Mesh.meshOnSphere(maxDiam=np.inf,
                                               maxNumNodes=+int(1e3),
                                               radius=1)

        # Set maximum diameter for each node
        maxDiamArray = 2 * np.sin(45 / 180.0 * np.pi / 2.0) * np.ones(
            (meshSphere0.N))
        maxDiamArray[0] = 2 * np.sin(1 / 180.0 * np.pi / 2.0)

        # Create refined sphere
        meshSphere1 = meshSphere0.refine(
            maxDiam=maxDiamArray,
            maxNumNodes=meshSphere0.N + 1000,
            transformation=mesher.geometrical.mapToHypersphere)

        # Make sure that the right number of nodes and simplices
        self.assertTrue(meshSphere1.nodes.shape[0] == 147)
        self.assertTrue(meshSphere1.triangles.shape[0] == 290)
Ejemplo n.º 5
0
        
print("Running mesh refinement example")
print("")


fig = plt.figure(1)
plt.clf()

print("Plot mesh")


# %% Create 1D mesh

nodes = np.linspace(0,1,4, dtype=np.float64).reshape((-1,1))
triangles = np.stack( (np.arange(0, nodes.size-1), np.arange(1,nodes.size)) ).transpose().astype(np.uintc)
meshm0 = mesher.Mesh( triangles, nodes )

ax = fig.add_subplot(321, )
ax.set_title( "Mesh refine 0" )    
plt.plot( meshm0.nodes[:,0], 0 * meshm0.nodes[:,0], marker="x" )

# Set maximum diameter for each node
maxDiamArray = 0.2 * np.ones( (meshm0.N) )
maxDiamArray[2] = 0.05
# Create refined sphere
meshm1 = meshm0.refine( maxDiam = maxDiamArray, maxNumNodes = meshm0.N + 50 )

ax = fig.add_subplot(322, )
ax.set_title( "Mesh refine 1" )    
plt.plot( meshm1.nodes[:,0], 0 * meshm1.nodes[:,0], marker="x" )
Ejemplo n.º 6
0
import numpy as np

print("Running test case: Implicit mesh")
print("")

fig = plt.figure(1)
plt.clf()

# %% 1D case

# Create 1D mesh
nodes = np.array([0, 2, 3, 4, 6]).reshape((-1, 1))
triangles = np.array([np.arange(0, 4), np.arange(1, 5)],
                     dtype=np.uintc).transpose().copy()
triangles = triangles[:, [1, 0]].copy()
mesh1 = mesher.Mesh(triangles=triangles, nodes=nodes)
mesh1.getBoundary()
# Get edges and neighbors
edges1 = mesher.Mesh.getEdges(mesh1.triangles,
                              mesh1.topD,
                              mesh1.topD,
                              libInstance=mesh1._libInstance)

# Get implicit mesh of mesh0
offset = np.array([-5], dtype=np.float64)
numPerDimension = np.array([3], dtype=np.uintc)
implicitMesh = mesher.ImplicitMesh(mesh1, offset, numPerDimension,
                                   mesh1.getNeighs())
mesh2 = implicitMesh.toFullMesh()
neighs2 = implicitMesh.getFullNeighs()
Ejemplo n.º 7
0
If a copy of the license was not distributed with this file, you can obtain one at https://opensource.org/licenses/BSD-3-Clause.

"""

import numpy as np
np.random.seed = 1

# %% Constructing the mesh

# Create mesh
import numpy as np
N = 500
nodes = np.linspace(0, 1, N).reshape((-1, 1))
simplices = np.stack((np.arange(0, N - 1), np.arange(1, N)), axis=1)
from fieldosophy import mesh as mesher
mesh = mesher.Mesh(triangles=simplices, nodes=nodes)

# %% Constructing a Matérn model

# Define the Matérn random field
r = 0.4  # Set correlation range (range for which two points have approximately 0.13 correlation)
nu = 1.5  # Set smoothness (basically the Hölder constant of realizations)
sigma = 2  # Set standard deviation
# Create MaternFEM object
from fieldosophy.GRF import FEM
fem = FEM.MaternFEM(mesh=mesh, childParams={'r': r}, nu=nu, sigma=sigma)

# Acquire realizations on nodes
Z = fem.generateRandom(2)
# Plot realizations
from matplotlib import pyplot as plt