Example #1
0
class unittest_get_group(TestCase):
    """unittest to extract a group as a Mesh object"""
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([1, 2]))
        self.mesh.node.add_node(np.array([2, 3]))
        self.mesh.node.add_node(np.array([3, 3]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))

    def test_ElementMat_1group(self):
        """unittest for 1 group"""

        elem_grp4 = self.mesh.element["Triangle3"].get_group([3])
        solution = np.array([[0, 1, 2], [1, 2, 3]])
        results = elem_grp4.connectivity
        testA = np.sum(abs(solution - results))
        msg = "Wrong output: returned " + str(results) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
class unittest_plot_mesh_field(TestCase):
    """unittest to get elements containing specific node(s)"""
    def setUp(self):

        self.simu = Simulation()
        self.out = Output(simu=self.simu)
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([0, 1]))
        self.mesh.node.add_node(np.array([1, 1]))
        self.mesh.node.add_node(np.array([2, 0]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 1, 3]), "Triangle3", group=int(2))

    def test_Mesh_ElementMat_NodeMat_3Tgl(self):

        field = np.array([1, 2, 3])
        self.out.plot_mesh_field(mesh=self.mesh,
                                 title="Permeability",
                                 field=field)
        fig = plt.gcf()
        fig.savefig(join(save_path, "test_plot_mesh_field.png"))
Example #3
0
    def test_ElementDict(self):
        # Init 1
        mesh = Mesh()
        mesh.element = ElementDict()
        mesh.element.connectivity = {"Triangle": np.array([[0, 1, 2], [1, 2, 3]])}
        mesh.element.tag = {"Triangle": np.array([1, 2])}
        mesh.element.nb_elem = {"Triangle": 2}
        mesh.element.nb_node_per_element = {"Triangle": 3}
        # Method test 1
        elem_tag = mesh.element.get_node2element(1)
        # Check results
        solution = np.array([1, 2])  # Warning, elements tags, not line position !
        testA = np.sum(abs(solution - elem_tag))
        msg = (
            "Wrong projection: returned "
            + str(elem_tag)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

        # Method test 2
        elem_tag = mesh.element.get_node2element(3)
        solution = np.array([2])
        testA = np.sum(abs(solution - elem_tag))
        msg = (
            "Wrong projection: returned "
            + str(elem_tag)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #4
0
    def __init__(
        self,
        mesh=None,
        parent_elem=None,
        parent_node=None,
        group_number=None,
        init_dict=None,
    ):
        """Constructor of the class. Can be use in two ways :
        - __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
            for Matrix, None will initialise the property with an empty Matrix
            for pyleecan type, None will call the default constructor
        - __init__ (init_dict = d) d must be a dictionnary wiht every properties as keys

        ndarray or list can be given for Vector and Matrix
        object or dict can be given for pyleecan Object"""

        if mesh == -1:
            mesh = Mesh()
        if init_dict is not None:  # Initialisation by dict
            check_init_dict(
                init_dict,
                ["mesh", "parent_elem", "parent_node", "group_number"])
            # Overwrite default value with init_dict content
            if "mesh" in list(init_dict.keys()):
                mesh = init_dict["mesh"]
            if "parent_elem" in list(init_dict.keys()):
                parent_elem = init_dict["parent_elem"]
            if "parent_node" in list(init_dict.keys()):
                parent_node = init_dict["parent_node"]
            if "group_number" in list(init_dict.keys()):
                group_number = init_dict["group_number"]
        # Initialisation by argument
        self.parent = None
        # mesh can be None, a Mesh object or a dict
        if isinstance(mesh, dict):
            # Check that the type is correct (including daughter)
            class_name = mesh.get("__class__")
            if class_name not in ["Mesh", "MeshFEMM", "MeshMat", "MeshForce"]:
                raise InitUnKnowClassError("Unknow class name " + class_name +
                                           " in init_dict for mesh")
            # Dynamic import to call the correct constructor
            module = __import__("pyleecan.Classes." + class_name,
                                fromlist=[class_name])
            class_obj = getattr(module, class_name)
            self.mesh = class_obj(init_dict=mesh)
        else:
            self.mesh = mesh
        # parent_elem can be None, a ndarray or a list
        set_array(self, "parent_elem", parent_elem)
        # parent_node can be None, a ndarray or a list
        set_array(self, "parent_node", parent_node)
        # group_number can be None, a ndarray or a list
        set_array(self, "group_number", group_number)

        # The class is frozen, for now it's impossible to add new properties
        self._freeze()
    def test_ElementDict_to_ElementDict(self):
        # Init 1
        mesh1 = Mesh()
        mesh1.element = ElementDict()
        mesh1.element.connectivity = {
            "Triangle": np.array([[0, 1, 2], [1, 2, 3]])
        }
        mesh1.element.tag = {"Triangle": np.array([1, 2])}
        mesh1.element.nb_elem = {"Triangle": 2}
        mesh1.element.nb_node_per_element = {"Triangle": 3}

        mesh2 = Mesh()
        mesh2.element = ElementMat()
        mesh2.element.connectivity = np.array([[0, 1, 2], [1, 2, 3]])
        mesh2.element.nb_elem = 2
        mesh2.element.nb_node_per_element = 3

        mesh_new = Mesh()
        mesh_new.element = ElementDict()

        # Method test 2
        mesh_new.element.convert_element(mesh1.element)
        # Check results 1
        solution = np.array([[0, 1, 2], [1, 2, 3]
                             ])  # Warning, elements tags, not line position !
        testA = np.sum(
            abs(solution - mesh_new.element.connectivity["Triangle"]))
        msg = ("Wrong projection: returned " +
               str(mesh_new.element.connectivity["Triangle"]) +
               ", expected: " + str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #6
0
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)
        self.mesh.node = NodeMat()

        self.other_mesh = Mesh()
        self.other_mesh.element["Triangle3"] = ElementMat(
            nb_node_per_element=3)
        self.other_mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)
        self.other_mesh.node = self.mesh.node
Example #7
0
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([1, 2]))
        self.mesh.node.add_node(np.array([2, 3]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3")
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3")
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.add_element([2, 1, 0], "Triangle3", group=int(3))
        self.mesh.add_element([1, 2, 3], "Triangle3", group=int(2))
        self.mesh.add_element([3, 1, 4], "Triangle3", group=int(2))

        self.mesh.node = NodeMat()
        self.mesh.node.add_node([0, 0])
        self.mesh.node.add_node([1, 0])
        self.mesh.node.add_node([0, 1])
        self.mesh.node.add_node([1, -1])
        self.mesh.node.add_node([2, -1])
Example #9
0
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([1, 2]))
        self.mesh.node.add_node(np.array([2, 3]))
        self.mesh.node.add_node(np.array([3, 3]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))
        self.mesh.add_element(np.array([4, 3]), "Segment2", group=int(2))
Example #10
0
    def __init__(self, name=None, mesh=None, solution=None, init_dict=None):
        """Constructor of the class. Can be use in two ways :
        - __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
            for Matrix, None will initialise the property with an empty Matrix
            for pyleecan type, None will call the default constructor
        - __init__ (init_dict = d) d must be a dictionnary wiht every properties as keys

        ndarray or list can be given for Vector and Matrix
        object or dict can be given for pyleecan Object"""

        if mesh == -1:
            mesh = Mesh()
        if solution == -1:
            solution = Solution()
        if init_dict is not None:  # Initialisation by dict
            check_init_dict(init_dict, ["name", "mesh", "solution"])
            # Overwrite default value with init_dict content
            if "name" in list(init_dict.keys()):
                name = init_dict["name"]
            if "mesh" in list(init_dict.keys()):
                mesh = init_dict["mesh"]
            if "solution" in list(init_dict.keys()):
                solution = init_dict["solution"]
        # Initialisation by argument
        self.parent = None
        self.name = name
        # mesh can be None, a Mesh object or a dict
        if isinstance(mesh, dict):
            self.mesh = Mesh(init_dict=mesh)
        else:
            self.mesh = mesh
        # solution can be None, a Solution object or a dict
        if isinstance(solution, dict):
            # Check that the type is correct (including daughter)
            class_name = solution.get("__class__")
            if class_name not in ["Solution", "SolutionFEMM"]:
                raise InitUnKnowClassError("Unknow class name " + class_name +
                                           " in init_dict for solution")
            # Dynamic import to call the correct constructor
            module = __import__("pyleecan.Classes." + class_name,
                                fromlist=[class_name])
            class_obj = getattr(module, class_name)
            self.solution = class_obj(init_dict=solution)
        else:
            self.solution = solution

        # The class is frozen, for now it's impossible to add new properties
        self._freeze()
    def setUp(self):

        self.simu = Simulation()
        self.out = Output(simu=self.simu)
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([0, 1]))
        self.mesh.node.add_node(np.array([1, 1]))
        self.mesh.node.add_node(np.array([2, 0]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 1, 3]), "Triangle3", group=int(2))
Example #12
0
class unittest_get_vertice(TestCase):
    """unittest for Mesh and Element get_all_connectivity methods"""
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Quad4"] = ElementMat(nb_node_per_element=4)
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([1, 2]))
        self.mesh.node.add_node(np.array([2, 3]))
        self.mesh.node.add_node(np.array([3, 3]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))
        self.mesh.add_element(np.array([4, 3]), "Segment2", group=int(2))

    def test_ElementMat_empty(self):
        """unittest with ElementMat object. Test for empty Mesh"""

        solution = 0
        result = self.mesh.get_vertice("Quad4")
        testA = result.size
        msg = ("Wrong output: returned " + str(result.size) + ", expected: " +
               str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, solution, msg=msg, delta=DELTA)

    def test_ElementMat_seg(self):
        """unittest with ElementMat object. Test for empty Mesh"""

        solution = 4
        result = self.mesh.get_vertice("Segment2")
        testA = result.size
        msg = ("Wrong output: returned " + str(result.size) + ", expected: " +
               str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, solution, msg=msg, delta=DELTA)

    def test_ElementMat_tgl(self):
        """unittest with ElementMat object. Test for empty Mesh"""

        solution = 18
        result = self.mesh.get_vertice("Triangle3")
        testA = result.size
        msg = ("Wrong output: returned " + str(result.size) + ", expected: " +
               str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, solution, msg=msg, delta=DELTA)
class unittest_get_all_connectivity(TestCase):
    """unittest for Mesh and Element get_all_connectivity methods. Indirect test add_element """

    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)
        self.mesh.add_element([2, 1, 0], "Triangle3", group=int(3))
        self.mesh.add_element([1, 2, 3], "Triangle3", group=int(2))
        self.mesh.add_element([3, 1, 4], "Triangle3", group=int(2))
        self.mesh.add_element([0, 1], "Segment2", group=int(3))

        self.mesh.node = NodeMat()
        self.mesh.node.add_node([0, 0])
        self.mesh.node.add_node([1, 0])
        self.mesh.node.add_node([0, 1])
        self.mesh.node.add_node([1, -1])
        self.mesh.node.add_node([2, -1])

    def test_ElementMat_NodeMat_1seg(self):
        """unittest with ElementDict and NodeMat objects, get 1 segment"""
        tag_test = self.mesh.add_element([2, 1], "Segment2", group=int(3))
        result = self.mesh.get_connectivity(tag_test)
        solution = np.array([2, 1])
        testA = np.sum(abs(result - solution))
        msg = "Wrong output: returned " + str(result) + ", expected: " + str(solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_NodeMat_1tgl(self):
        """unittest with ElementDict and NodeMat objects, with input None"""
        result = self.mesh.get_connectivity(None)

        testA = result is None
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(None)
        self.assertTrue(testA, msg=msg)

    def test_ElementMat_NodeMat_1seg_stupid(self):
        """unittest with ElementDict and NodeMat objects, with only 1 segment"""
        result = self.mesh.get_connectivity(
            -99999
        )  # We test what happened with stupid entry
        # Check result
        testA = result is None
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(None)
        self.assertTrue(testA, msg=msg)
Example #14
0
class unittest_get_coord(TestCase):
    """unittest for NodeMat get_node methods"""
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([1, 2]))
        self.mesh.node.add_node(np.array([2, 3]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3")
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3")

    def test_NodeMat_1node(self):
        """unittest for a node"""
        node_tags = self.mesh.get_connectivity(1)
        # Method test 1
        coord = self.mesh.node.get_coord(node_tags)
        # Check result
        solution = np.array([[1, 0], [1, 2], [2, 3]])
        testA = np.sum(abs(solution - coord))
        msg = "Wrong output: returned " + str(coord) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_NodeMat_false(self):
        """unittest for a false node tag"""

        coord = self.mesh.node.get_coord(-999)
        solution = None
        testA = coord is None
        msg = "Wrong out: returned " + str(coord) + ", expected: " + str(
            solution)
        self.assertTrue(testA, msg=msg)

    def test_NodeMat_None(self):
        """unittest for a None node tag"""

        coord = self.mesh.node.get_coord(None)
        solution = None
        testA = coord is None
        msg = "Wrong output: returned " + str(coord) + ", expected: " + str(
            solution)
        self.assertTrue(testA, msg=msg)
Example #15
0
    def test_ElementDict_NodeMat(self):
        """unittest with ElementDict and NodeMat objects"""
        # Init
        mesh = Mesh()
        mesh.element = ElementDict()
        mesh.node = NodeMat()
        mesh.node.coordinate = np.array([[0, 0], [1, 0], [1, 2], [2, 3]])
        mesh.element.connectivity = {
            "Triangle": np.array([[0, 1, 2], [1, 2, 3]])
        }
        mesh.element.tag = {"Triangle": np.array([1, 2])}
        mesh.element.nb_elem = {"Triangle": 2}
        mesh.element.nb_node_per_element = {"Triangle": 3}
        # Method test 1
        node_tags = mesh.element.get_node_tags(2)
        # Check result
        solution = np.array([1, 2, 3])
        testA = np.sum(abs(solution - node_tags))
        msg = ("Wrong projection: returned " + str(node_tags) +
               ", expected: " + str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

        # Method test 2
        node_tags = mesh.element.get_node_tags(np.array([1, 2]))
        # Check result
        solution = np.array([0, 1, 2, 3])
        testA = np.sum(abs(solution - node_tags))
        msg = ("Wrong projection: returned " + str(node_tags) +
               ", expected: " + str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

        # Method test 3
        node_tags = mesh.element.get_node_tags()
        # Check result
        solution = np.array([0, 1, 2, 3])
        testA = np.sum(abs(solution - node_tags))
        msg = ("Wrong projection: returned " + str(node_tags) +
               ", expected: " + str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #16
0
 def test_NodeMat_ElementMat(self):
     """unittest with ElementMat and NodeMat objects"""
     # Init
     mesh = Mesh()
     mesh.element = ElementMat()
     mesh.node = NodeMat()
     mesh.node.coordinate = np.array([[0, 0], [1, 0], [1, 2], [2, 3]])
     mesh.element.connectivity = np.array([[0, 1, 2], [1, 2, 3]])
     mesh.element.nb_elem = 2
     mesh.element.nb_node_per_element = 3
     node_tags = mesh.element.get_node_tags(1)
     # Method test 1
     nodes_coord = mesh.node.get_coord(node_tags)
     # Check result
     solution = np.array([[1, 0], [1, 2], [2, 3]])
     testA = np.sum(abs(solution - nodes_coord))
     msg = ("Wrong projection: returned " + str(node_tags) +
            ", expected: " + str(solution))
     DELTA = 1e-10
     self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #17
0
def set_submesh(self, group_number):
    """Define a mesh object as submesh of parent mesh object

     Parameters
     ----------
     self : Mesh
         an Mesh object
     group_number : int
         a group number which define the elements which constitute the submesh

     Returns
     -------

     """
    submesh = Mesh()
    submesh.element = self.element.get_group(
        group_number
    )  # Create a new Element object which is restrained to group_number
    submesh.node = self.node.get_group(
        element=submesh.element
    )  # Create a new Node object which corresponds to selection of element
Example #18
0
 def test_ElementMat(self):
     # Init 1
     mesh = Mesh()
     mesh.element = ElementMat()
     mesh.element.connectivity = np.array(
         [[11, 12, 13], [0, 1, 2], [1, 2, 3], [120, 11, 12]]
     )
     mesh.element.nb_elem = 2
     mesh.element.nb_node_per_element = 3
     # Method test 1
     elem_tag = mesh.element.get_node2element(1)
     # Check results
     solution = np.array([1, 2])  # In this case, element tag = line position
     testA = np.sum(abs(solution - elem_tag))
     msg = (
         "Wrong projection: returned "
         + str(elem_tag)
         + ", expected: "
         + str(solution)
     )
     DELTA = 1e-10
     self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #19
0
    def test_ElementMat_NodeMat(self):
        # Init 1
        # Init
        mesh = Mesh()
        mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        mesh.node = NodeMat()
        mesh.node.add_node(np.array([0, 0]))
        mesh.node.add_node(np.array([1, 0]))
        mesh.node.add_node(np.array([1, 2]))
        mesh.node.add_node(np.array([2, 3]))
        mesh.node.add_node(np.array([3, 3]))

        mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))

        # Method test 1
        mesh_grp4 = mesh.set_submesh([3])
        # Check results
        solution = np.array([[0, 1, 2], [1, 2, 3]])
        results = mesh_grp4.element["Triangle3"].connectivity
        testA = np.sum(abs(solution - results))
        msg = "Wrong result: returned " + str(results) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

        # Method test 2
        mesh_grp4 = mesh.set_submesh([3, 2])
        # Check results
        solution = np.array([2, 3])
        results = mesh_grp4.element["Segment2"].connectivity
        testA = np.sum(abs(solution - results))
        msg = "Wrong result: returned " + str(results) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #20
0
class unittest_get_node2element(TestCase):
    """unittest to get elements containing specific node(s)"""

    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))

    def test_ElementMat_1node(self):
        """unittest for one existing node """
        elem_tag = self.mesh.element["Triangle3"].get_node2element(1)
        solution = np.array([0, 1])
        testA = np.sum(abs(solution - elem_tag))
        msg = "Wrong output: returned " + str(elem_tag) + ", expected: " + str(solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_fakenode(self):
        """unittest for one non-existing node """
        elem_tag = self.mesh.element["Triangle3"].get_node2element(-99)
        solution = None
        testA = np.sum(abs(solution - elem_tag))
        msg = "Wrong output: returned " + str(elem_tag) + ", expected: " + str(solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_None(self):
        """unittest for None input """
        elem_tag = self.mesh.element["Triangle3"].get_node2element(None)
        solution = None
        testA = np.sum(abs(solution - elem_tag))
        msg = "Wrong output: returned " + str(elem_tag) + ", expected: " + str(solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
class unittest_get_all_node_coord(TestCase):
    """unittest for Mesh get_all_node_coord method. Indirect testing of get_group, get_all_node_tags, get_coord"""
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.add_element([2, 1, 0], "Triangle3", group=int(3))
        self.mesh.add_element([1, 2, 3], "Triangle3", group=int(2))
        self.mesh.add_element([3, 1, 4], "Triangle3", group=int(2))

        self.mesh.node = NodeMat()
        self.mesh.node.add_node([0, 0])
        self.mesh.node.add_node([1, 0])
        self.mesh.node.add_node([0, 1])
        self.mesh.node.add_node([1, -1])
        self.mesh.node.add_node([2, -1])

    def test_NodeMat_ElementMat_coord(self):
        """unittest with NodeMat and ElementMat objects"""

        result, res_tags = self.mesh.get_all_node_coord()
        solution = np.array([[0, 0], [1, 0], [0, 1], [1, -1], [2, -1]])
        testA = np.sum(abs(result - solution))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_NodeMat_ElementMat_tags(self):
        """unittest with NodeMat and ElementMat objects"""

        result, res_tags = self.mesh.get_all_node_coord()
        solution = np.array([0, 1, 2, 3, 4])
        testA = np.sum(abs(res_tags - solution))
        msg = "Wrong result: returned " + str(res_tags) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_NodeMat_ElementMat_group(self):
        """unittest with NodeMat and ElementMat objects"""

        result, res_tags = self.mesh.get_all_node_coord(2)
        solution = np.array([1, 2, 3, 4])
        testA = np.sum(abs(res_tags - solution))
        msg = "Wrong result: returned " + str(res_tags) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #22
0
class unittest_get_node_tags(TestCase):
    """unittest for elements and nodes getter methods"""
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)
        self.mesh.node = NodeMat()
        self.mesh.node.add_node(np.array([0, 0]))
        self.mesh.node.add_node(np.array([1, 0]))
        self.mesh.node.add_node(np.array([1, 2]))
        self.mesh.node.add_node(np.array([2, 3]))
        self.mesh.node.add_node(np.array([3, 3]))

        self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
        self.mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))
        self.mesh.add_element(np.array([4, 3]), "Segment2", group=int(2))

    def test_ElementMat_NodeMat_Triangle3(self):
        """unittest with ElementMat and NodeMat objects, only Triangle3 elements are defined"""

        node_tags = self.mesh.get_node_tags(
            elem_tag=np.array([1, 2], dtype=int))
        solution = np.array([1, 2, 3, 4])

        testA = np.sum(abs(solution - node_tags))
        msg = ("Wrong projection: returned " + str(node_tags) +
               ", expected: " + str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_NodeMat_MixedElement(self):
        """unittest with ElementMat and NodeMat objects, both Triangle3 and Segment2 elements are defined"""
        # Method test 2
        node_tags = self.mesh.get_node_tags(np.array([2, 3]))
        # Check result
        solution = np.array([2, 3, 4])
        testA = np.sum(abs(solution - node_tags))
        msg = ("Wrong projection: returned " + str(node_tags) +
               ", expected: " + str(solution))
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #23
0
 def setUp(self):
     self.mesh = Mesh()
     self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
     self.mesh.add_element(np.array([0, 1, 2]), "Triangle3", group=int(3))
     self.mesh.add_element(np.array([1, 2, 3]), "Triangle3", group=int(3))
     self.mesh.add_element(np.array([4, 2, 3]), "Triangle3", group=int(2))
class unittest_get_all_connectivity(TestCase):
    """unittest for Mesh and Element get_all_connectivity methods"""
    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)

    def test_ElementMat_empty(self):
        """unittest with ElementMat object. Test for empty Mesh"""

        solution = np.array([])
        result, tags = self.mesh.get_all_connectivity("Segment2")
        testA = result.size
        msg = "Wrong output: returned " + str(
            result.size) + ", expected: " + str(0)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_1seg(self):
        """unittest with ElementMat object. Test for 1 segment."""

        node_tags = np.array([0, 1])
        self.mesh.add_element(node_tags, "Segment2")
        result, tags = self.mesh.get_all_connectivity("Segment2")

        testA = np.sum(abs(result - node_tags))
        msg = "Wrong output: returned " + str(result) + ", expected: " + str(
            node_tags)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_2seg(self):
        """unittest with ElementMat object. Test with 2 segment."""

        self.mesh.add_element([0, 1], "Segment2")
        self.mesh.add_element([1, 2], "Segment2")
        result, tags = self.mesh.get_all_connectivity("Segment2")
        solution = np.array([[0, 1], [1, 2]])
        testA = np.sum(abs(result - solution))
        msg = "Wrong output: returned " + str(result) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_2seg_1tgl(self):
        """unittest with ElementMat object. Test with 2 segment and 1 tgl."""

        self.mesh.add_element([0, 1], "Segment2")
        self.mesh.add_element([1, 2], "Segment2")
        node_tags = np.array([1, 2, 3])
        self.mesh.add_element(node_tags, "Triangle3")
        result, tags = self.mesh.get_all_connectivity("Triangle3")
        testA = np.sum(abs(result - node_tags))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(
            node_tags)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_2seg_2tgl(self):
        """unittest with ElementMat object. Test with 2 segment and 2 tgl."""

        self.mesh.add_element([0, 1], "Segment2")
        self.mesh.add_element([1, 2], "Segment2")
        self.mesh.add_element([1, 2, 3], "Triangle3")
        self.mesh.add_element([2, 3, 0], "Triangle3")
        result, tags = self.mesh.get_all_connectivity("Triangle3")
        solution = np.array([[1, 2, 3], [2, 3, 0]])
        testA = np.sum(abs(result - solution))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_3seg_2tgl_1group(self):
        """unittest with ElementMat object. Test for 1 triangle in a group."""

        self.mesh.add_element([0, 1], "Segment2")
        self.mesh.add_element([1, 2], "Segment2")
        self.mesh.add_element([1, 2, 3], "Triangle3")
        self.mesh.add_element([2, 3, 0], "Triangle3")
        node_tags = np.array([2, 1, 0])
        self.mesh.add_element(node_tags, "Triangle3", group=3)
        result, tags = self.mesh.get_all_connectivity("Triangle3",
                                                      group=np.array(
                                                          [3], dtype=int))
        solution = node_tags
        testA = np.sum(abs(result - solution))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

        result, tags = self.mesh.get_all_connectivity("Triangle3", group=3)
        solution = node_tags
        testA = np.sum(abs(result - solution))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_ElementMat_3seg_2tgl_2group(self):
        """unittest with ElementMat object. Test for 2 triangle in a group."""

        self.mesh.add_element([0, 1], "Segment2")
        self.mesh.add_element([1, 2], "Segment2")
        self.mesh.add_element([1, 2, 3], "Triangle3")
        self.mesh.add_element([2, 3, 0], "Triangle3", group=3)
        self.mesh.add_element([2, 1, 0], "Triangle3", group=3)
        result, tags = self.mesh.get_all_connectivity("Triangle3", group=3)
        solution = np.array([[2, 3, 0], [2, 1, 0]])
        testA = np.sum(abs(result - solution))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(
            solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #25
0
def get_meshsolution(self, is_get_mesh, is_save_FEA, save_path, j_t0):
    """Load the mesh data and solution data. FEMM must be working and a simulation must have been solved.

    Parameters
    ----------
    self : MagFEMM
        a MagFEMM object
    is_get_mesh : bool
        1 to load the mesh and solution into the simulation
    is_save_FEA : bool
        1 to save the mesh and solution into a .json file
    j_t0 : int
        Targeted time step

    Returns
    -------
    res_path: str
        path to the result folder
    """

    idworker = "1"  # For parallelization TODO

    path_txt = join(MAIN_DIR, "Functions", "FEMM") + "\\"
    path_txt_lua = path_txt.replace("\\", "/")
    path_lua_in = join(path_txt, "get_mesh_data_FEMM.lua")
    path_lua_out = join(save_path, "get_mesh_data_FEMM" + idworker + ".lua")
    path_txt_out = save_path + "\\"
    path_txt_out = path_txt_out.replace("\\", "/")

    # Create a new LUA script with current paths
    file_lua = open(path_lua_in, "r")
    text_lua = file_lua.read()
    file_lua.close()
    text_lua = text_lua.replace("my_path_txt", path_txt_out)
    text_lua = text_lua.replace("my_id_worker", idworker)

    file_lua_out = open(path_lua_out, "w")
    file_lua_out.write(text_lua)
    file_lua_out.close()

    # Run the LUA externally using FEMM LUA console and store the data in the
    # temporary text files
    path_lua_out2 = path_lua_out.replace("\\", "/")
    callfemm('dofile("' + path_lua_out2 + '")')

    # Delete the LUA script
    os.remove(path_lua_out)

    # Read the nodes and elements files
    path_node = join(save_path, "nodes" + idworker + ".txt")
    path_element = join(save_path, "elements" + idworker + ".txt")
    listNd0 = np.loadtxt(path_node, delimiter=" ")
    listElem0 = np.loadtxt(path_element, dtype="i", delimiter=" ")
    NbNd = len(listNd0)
    NbElem = len(listElem0)

    # Node list
    listNd = np.zeros(shape=(NbNd, 3))
    listNd[:, 0] = listNd0[:, 0]
    listNd[:, 1] = listNd0[:, 1]

    # Element list
    # listElem = np.zeros(shape=(NbElem, 3))
    listElem = listElem0[:, 0:3] - 1

    # Delete text files
    os.remove(path_node)
    os.remove(path_element)

    # Read the results file
    path_results = join(save_path, "results" + idworker + ".txt")
    results = np.loadtxt(path_results, delimiter=" ")

    # Delete text files
    os.remove(path_results)

    # Create Mesh and Solution dictionaries
    if (not self.is_sliding_band) or (j_t0 == 0):
        mesh = Mesh()
        mesh.element["Triangle3"] = ElementMat(
            connectivity=listElem,
            nb_elem=NbElem,
            group=listElem0[:, 6],
            nb_node_per_element=3,
            tag=np.linspace(0, NbElem - 1, NbElem),
        )
        mesh.node = NodeMat(
            coordinate=listNd[:, 0:2], nb_node=NbNd, tag=np.linspace(0, NbNd - 1, NbNd)
        )

        mesh.group = np.unique(listElem0[:, 6])
    else:
        mesh = None

    B = results[:, 0:2]
    H = results[:, 2:4]
    mu = results[:, 4]
    Az = results[:, 5]

    solution = Solution()
    solution.set_field(field_value=B, field_name="B", field_type="face")
    solution.set_field(field_value=H, field_name="H", field_type="face")
    solution.set_field(field_value=mu, field_name="mu", field_type="face")
    solution.set_field(field_value=Az, field_name="Az", field_type="nodal")

    return mesh, solution
Example #26
0
    def __init__(
            self,
            time=None,
            angle=None,
            Nt_tot=None,
            Na_tot=None,
            Br=None,
            Bt=None,
            Tem=None,
            Tem_av=None,
            Tem_rip=None,
            Phi_wind_stator=None,
            emf=None,
            mesh=list(),
            init_dict=None,
    ):
        """Constructor of the class. Can be use in two ways :
        - __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
            for Matrix, None will initialise the property with an empty Matrix
            for pyleecan type, None will call the default constructor
        - __init__ (init_dict = d) d must be a dictionnary wiht every properties as keys

        ndarray or list can be given for Vector and Matrix
        object or dict can be given for pyleecan Object"""

        if init_dict is not None:  # Initialisation by dict
            check_init_dict(
                init_dict,
                [
                    "time",
                    "angle",
                    "Nt_tot",
                    "Na_tot",
                    "Br",
                    "Bt",
                    "Tem",
                    "Tem_av",
                    "Tem_rip",
                    "Phi_wind_stator",
                    "emf",
                    "mesh",
                ],
            )
            # Overwrite default value with init_dict content
            if "time" in list(init_dict.keys()):
                time = init_dict["time"]
            if "angle" in list(init_dict.keys()):
                angle = init_dict["angle"]
            if "Nt_tot" in list(init_dict.keys()):
                Nt_tot = init_dict["Nt_tot"]
            if "Na_tot" in list(init_dict.keys()):
                Na_tot = init_dict["Na_tot"]
            if "Br" in list(init_dict.keys()):
                Br = init_dict["Br"]
            if "Bt" in list(init_dict.keys()):
                Bt = init_dict["Bt"]
            if "Tem" in list(init_dict.keys()):
                Tem = init_dict["Tem"]
            if "Tem_av" in list(init_dict.keys()):
                Tem_av = init_dict["Tem_av"]
            if "Tem_rip" in list(init_dict.keys()):
                Tem_rip = init_dict["Tem_rip"]
            if "Phi_wind_stator" in list(init_dict.keys()):
                Phi_wind_stator = init_dict["Phi_wind_stator"]
            if "emf" in list(init_dict.keys()):
                emf = init_dict["emf"]
            if "mesh" in list(init_dict.keys()):
                mesh = init_dict["mesh"]
        # Initialisation by argument
        self.parent = None
        # time can be None, a ndarray or a list
        set_array(self, "time", time)
        # angle can be None, a ndarray or a list
        set_array(self, "angle", angle)
        self.Nt_tot = Nt_tot
        self.Na_tot = Na_tot
        # Br can be None, a ndarray or a list
        set_array(self, "Br", Br)
        # Bt can be None, a ndarray or a list
        set_array(self, "Bt", Bt)
        # Tem can be None, a ndarray or a list
        set_array(self, "Tem", Tem)
        self.Tem_av = Tem_av
        self.Tem_rip = Tem_rip
        # Phi_wind_stator can be None, a ndarray or a list
        set_array(self, "Phi_wind_stator", Phi_wind_stator)
        # emf can be None, a ndarray or a list
        set_array(self, "emf", emf)
        # mesh can be None or a list of Mesh object
        self.mesh = list()
        if type(mesh) is list:
            for obj in mesh:
                if obj is None:  # Default value
                    self.mesh.append(Mesh())
                elif isinstance(obj, dict):
                    # Check that the type is correct (including daughter)
                    class_name = obj.get("__class__")
                    if class_name not in [
                            "Mesh", "MeshFEMM", "MeshMat", "MeshForce"
                    ]:
                        raise InitUnKnowClassError("Unknow class name " +
                                                   class_name +
                                                   " in init_dict for mesh")
                    # Dynamic import to call the correct constructor
                    module = __import__("pyleecan.Classes." + class_name,
                                        fromlist=[class_name])
                    class_obj = getattr(module, class_name)
                    self.mesh.append(class_obj(init_dict=obj))
                else:
                    self.mesh.append(obj)
        elif mesh is None:
            self.mesh = list()
        else:
            self.mesh = mesh

        # The class is frozen, for now it's impossible to add new properties
        self._freeze()
Example #27
0
def solve_FEMM(self, output, sym, FEMM_dict):

    # Loading parameters for readibilitys
    angle = output.mag.angle

    L1 = output.simu.machine.stator.comp_length()
    Nt_tot = output.mag.Nt_tot  # Number of time step
    Na_tot = output.mag.Na_tot  # Number of angular step
    save_path = self.get_path_save(output)

    if (hasattr(output.simu.machine.stator, "winding")
            and output.simu.machine.stator.winding is not None):
        qs = output.simu.machine.stator.winding.qs  # Winding phase number
        Npcpp = output.simu.machine.stator.winding.Npcpp
        Phi_wind_stator = zeros((Nt_tot, qs))
    else:
        Phi_wind_stator = None

    # Create the mesh
    femm.mi_createmesh()

    # Initialize results matrix
    Br = zeros((Nt_tot, Na_tot))
    Bt = zeros((Nt_tot, Na_tot))
    Tem = zeros((Nt_tot, 1))

    lam_int = output.simu.machine.get_lamination(True)
    lam_ext = output.simu.machine.get_lamination(False)
    Rgap_mec_int = lam_int.comp_radius_mec()
    Rgap_mec_ext = lam_ext.comp_radius_mec()

    if self.is_get_mesh or self.is_save_FEA:
        meshFEMM = [Mesh() for ii in range(Nt_tot)]
        solutionFEMM = [Solution() for ii in range(Nt_tot)]
    else:
        meshFEMM = [Mesh()]
        solutionFEMM = [Solution()]

    # Compute the data for each time step
    for ii in range(Nt_tot):
        # Update rotor position and currents
        update_FEMM_simulation(
            output=output,
            materials=FEMM_dict["materials"],
            circuits=FEMM_dict["circuits"],
            is_mmfs=self.is_mmfs,
            is_mmfr=self.is_mmfr,
            j_t0=ii,
            is_sliding_band=self.is_sliding_band,
        )
        # try "previous solution" for speed up of FEMM calculation
        if self.is_sliding_band:
            try:
                base = basename(self.get_path_save_fem(output))
                ans_file = splitext(base)[0] + ".ans"
                femm.mi_setprevious(ans_file, 0)
            except:
                pass

        # Run the computation
        femm.mi_analyze()
        femm.mi_loadsolution()

        # Get the flux result
        if self.is_sliding_band:
            for jj in range(Na_tot):
                Br[ii, jj], Bt[ii,
                               jj] = femm.mo_getgapb("bc_ag2",
                                                     angle[jj] * 180 / pi)
        else:
            Rag = (Rgap_mec_ext + Rgap_mec_int) / 2
            for jj in range(Na_tot):
                B = femm.mo_getb(Rag * np.cos(angle[jj]),
                                 Rag * np.sin(angle[jj]))
                Br[ii,
                   jj] = B[0] * np.cos(angle[jj]) + B[1] * np.sin(angle[jj])
                Bt[ii,
                   jj] = -B[0] * np.sin(angle[jj]) + B[1] * np.cos(angle[jj])

        # Compute the torque
        Tem[ii] = comp_FEMM_torque(FEMM_dict, sym=sym)

        if (hasattr(output.simu.machine.stator, "winding")
                and output.simu.machine.stator.winding is not None):
            # Phi_wind computation
            Phi_wind_stator[ii, :] = comp_FEMM_Phi_wind(
                qs,
                Npcpp,
                is_stator=True,
                Lfemm=FEMM_dict["Lfemm"],
                L1=L1,
                sym=sym)

        # Load mesh data & solution
        if self.is_get_mesh or self.is_save_FEA:
            meshFEMM[ii], solutionFEMM[ii] = self.get_meshsolution(
                self.is_get_mesh, self.is_save_FEA, save_path, ii)

    # Shift to take into account stator position
    roll_id = int(self.angle_stator * Na_tot / (2 * pi))
    Br = roll(Br, roll_id, axis=1)
    Bt = roll(Bt, roll_id, axis=1)

    # Store the results
    output.mag.Br = Br
    output.mag.Bt = Bt
    output.mag.Tem = Tem
    output.mag.Tem_av = mean(Tem)
    if output.mag.Tem_av != 0:
        output.mag.Tem_rip = abs(
            (np_max(Tem) - np_min(Tem)) / output.mag.Tem_av)
    output.mag.Phi_wind_stator = Phi_wind_stator
    output.mag.FEMM_dict = FEMM_dict

    if self.is_get_mesh:
        cond = (not self.is_sliding_band) or (Nt_tot == 1)
        output.mag.meshsolution = MeshSolution(
            name="FEMM_magnetic_mesh",
            mesh=meshFEMM,
            solution=solutionFEMM,
            is_same_mesh=cond,
        )

    if self.is_save_FEA:
        save_path_fea = join(save_path, "MeshSolutionFEMM.json")
        output.mag.meshsolution.save(save_path_fea)

    if (hasattr(output.simu.machine.stator, "winding")
            and output.simu.machine.stator.winding is not None):
        # Electromotive forces computation (update output)
        self.comp_emf()
    else:
        output.mag.emf = None
Example #28
0
def get_meshsolution(self, is_get_mesh, is_save_FEA, save_path, j_t0):
    """Load the mesh data and solution data. FEMM must be working and a simulation must have been solved.

    Parameters
    ----------
    self : MagFEMM
        a MagFEMM object
    is_get_mesh : bool
        1 to load the mesh and solution into the simulation
    is_save_FEA : bool
        1 to save the mesh and solution into a .json file
    j_t0 : int
        Targeted time step

    Returns
    -------
    res_path: str
        path to the result folder
    """
    # TODO: Not saving the mesh (only the solution) when the sliding band is activated

    idworker = "1"  # For parallelization TODO

    path_txt = join(MAIN_DIR, "Functions", "FEMM") + "\\"
    path_txt_lua = path_txt.replace("\\", "/")
    path_lua_in = join(path_txt, "get_mesh_data_FEMM.lua")
    path_lua_out = join(save_path, "get_mesh_data_FEMM" + idworker + ".lua")
    path_txt_out = save_path + "\\"
    path_txt_out = path_txt_out.replace("\\", "/")

    # Create a new LUA script with current paths
    file_lua = open(path_lua_in, "r")
    text_lua = file_lua.read()
    file_lua.close()
    text_lua = text_lua.replace("my_path_txt", path_txt_out)
    text_lua = text_lua.replace("my_id_worker", idworker)

    file_lua_out = open(path_lua_out, "w")
    file_lua_out.write(text_lua)
    file_lua_out.close()

    # Run the LUA externally using FEMM LUA console and store the data in the
    # temporary text files
    path_lua_out2 = path_lua_out.replace("\\", "/")
    callfemm('dofile("' + path_lua_out2 + '")')

    # Delete the LUA script
    os.remove(path_lua_out)

    # Read the nodes and elements files
    path_node = join(save_path, "nodes" + idworker + ".txt")
    path_element = join(save_path, "elements" + idworker + ".txt")
    listNd0 = np.loadtxt(path_node, delimiter=" ")
    listElem0 = np.loadtxt(path_element, dtype="i", delimiter=" ")
    NbNd = len(listNd0)
    NbElem = len(listElem0)

    # Node list
    listNd = np.zeros(shape=(NbNd, 3))
    listNd[:, 0] = listNd0[:, 0]
    listNd[:, 1] = listNd0[:, 1]

    # Element list
    # listElem = np.zeros(shape=(NbElem, 3))
    listElem = listElem0[:, 0:3] - 1

    # Delete text files
    os.remove(path_node)
    os.remove(path_element)

    # Read the results file
    path_results = join(save_path, "results" + idworker + ".txt")
    results = np.loadtxt(path_results, delimiter=" ")

    # Delete text files
    os.remove(path_results)

    # Save data
    if is_get_mesh:

        # Create Mesh and Solution dictionaries
        mesh = Mesh()
        mesh.element = ElementMat(
            connectivity=listElem,
            nb_elem=NbElem,
            group=listElem0[:, 6],
            nb_node_per_element=3,
        )
        mesh.node = NodeMat(coordinate=listNd[:, 0:2], nb_node=NbNd)

        solution = SolutionFEMM(B=results[:, 0:2], H=results[:, 2:4], mu=results[:, 4])

        meshFEMM = MeshSolution(name="FEMM_magnetic_mesh", mesh=mesh, solution=solution)

        if is_save_FEA:
            save_path_fea = join(save_path, "meshFEMM" + str(j_t0) + ".json")
            meshFEMM.save(save_path_fea)

        return meshFEMM
Example #29
0
class unittest_add_element(TestCase):
    """unittest for add_element methods in Mesh and Element classes"""

    def setUp(self):
        self.mesh = Mesh()
        self.mesh.element["Triangle3"] = ElementMat(nb_node_per_element=3)
        self.mesh.element["Segment2"] = ElementMat(nb_node_per_element=2)

    def test_Mesh_ElementMat_1seg(self):
        """unittest with ElementMat and only 1 segment element"""

        node_tags = np.array([0, 1])
        self.mesh.add_element(node_tags, "Segment2")
        # Check result
        testA = np.sum(abs(self.mesh.element["Segment2"].connectivity - node_tags))
        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Segment2"].connectivity)
            + ", expected: "
            + str(node_tags)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Segment2"].nb_elem)
            + ", expected: "
            + str(1)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(
            self.mesh.element["Segment2"].nb_elem, 1, msg=msg, delta=DELTA
        )

    def test_Mesh_ElementMat_2elem(self):
        """unittest with ElementMat and 2 segment element"""

        node_tags = np.array([0, 1])
        self.mesh.add_element(node_tags, "Segment2")
        node_tags = np.array([1, 2])
        self.mesh.add_element(node_tags, "Segment2")

        # Check result
        solution = np.array([[0, 1], [1, 2]])
        testA = np.sum(abs(self.mesh.element["Segment2"].connectivity - solution))
        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Segment2"].connectivity)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_Mesh_ElementMat_2elem_1tgl(self):
        """unittest with ElementMat and 2 segment element and 1 triangle"""

        self.mesh.add_element(np.array([0, 1]), "Segment2")
        self.mesh.add_element(np.array([1, 2]), "Segment2")
        solution = np.array([1, 2, 3])
        self.mesh.add_element(solution, "Triangle3")

        testA = np.sum(abs(self.mesh.element["Triangle3"].connectivity - solution))
        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Triangle3"].connectivity)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_Mesh_ElementMat_2elem_1tgl_add_seg_exist(self):
        """unittest with ElementMat and 2 segment element and 1 triangle, try to add an already existing segment."""

        self.mesh.add_element(np.array([0, 1]), "Segment2")
        self.mesh.add_element(np.array([1, 2]), "Segment2")
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3")
        self.mesh.add_element(np.array([0, 1]), "Segment2")  # already exist

        solution = np.array([[0, 1], [1, 2]])
        testA = np.sum(abs(self.mesh.element["Segment2"].connectivity - solution))
        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Segment2"].connectivity)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_Mesh_ElementMat_2elem_1tgl_add_tgl_exist(self):
        """unittest with ElementMat and 2 segment element and 1 triangle, try to add an already existing triangle."""

        self.mesh.add_element(np.array([0, 1]), "Segment2")
        self.mesh.add_element(np.array([1, 2]), "Segment2")
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3")
        self.mesh.add_element(np.array([2, 3, 1]), "Triangle3")  # already exist

        solution = np.array([1, 2, 3])
        testA = np.sum(abs(self.mesh.element["Triangle3"].connectivity - solution))
        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Triangle3"].connectivity)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_Mesh_ElementMat_2elem_2tgl(self):
        """unittest with ElementMat and 2 segment element and 1 triangle, add 1 triangle."""

        self.mesh.add_element(np.array([0, 1]), "Segment2")
        self.mesh.add_element(np.array([1, 2]), "Segment2")
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3")
        self.mesh.add_element(np.array([2, 3, 0]), "Triangle3")  # already exist

        solution = np.array([[1, 2, 3], [2, 3, 0]])
        testA = np.sum(abs(self.mesh.element["Triangle3"].connectivity - solution))
        msg = (
            "Wrong result: returned "
            + str(self.mesh.element["Triangle3"].connectivity)
            + ", expected: "
            + str(solution)
        )
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)

    def test_Mesh_ElementMat_2elem_2tgl_add_tgl_group(self):
        """unittest with ElementMat and 2 segment element and 1 triangle, add 1 triangle with a group number."""

        self.mesh.add_element(np.array([0, 1]), "Segment2")
        self.mesh.add_element(np.array([1, 2]), "Segment2")
        self.mesh.add_element(np.array([1, 2, 3]), "Triangle3")
        self.mesh.add_element(np.array([2, 3, 0]), "Triangle3")  # already exist
        self.mesh.add_element(np.array([2, 0, 1]), "Triangle3", group=3)

        solution = np.array([-1, -1, 3], dtype=int)
        result = self.mesh.element["Triangle3"].group
        testA = (result == solution).all()
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(solution)
        self.assertTrue(testA, msg=msg)

    def test_Mesh_ElementMat_add_stupid(self):
        """unittest with ElementMat and 2 segment element and 1 triangle, add 1 triangle with a group number."""

        self.mesh.add_element(np.array([0, 1]), "Segment2")
        self.mesh.add_element(None, "Segment2")
        self.mesh.add_element(np.array([0, 1, 2]), "Segment2")
        self.mesh.add_element(np.array([1, 1]), "Segment2")

        solution = np.array([0, 1], dtype=int)
        result = self.mesh.element["Segment2"].connectivity
        testA = np.sum(abs(result - solution))
        msg = "Wrong result: returned " + str(result) + ", expected: " + str(solution)
        DELTA = 1e-10
        self.assertAlmostEqual(testA, 0, msg=msg, delta=DELTA)
Example #30
0
class MeshSolution(FrozenClass):
    """To associate a Mesh with one or several solutions"""

    VERSION = 1

    # save method is available in all object
    save = save

    def __init__(self, name=None, mesh=None, solution=None, init_dict=None):
        """Constructor of the class. Can be use in two ways :
        - __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
            for Matrix, None will initialise the property with an empty Matrix
            for pyleecan type, None will call the default constructor
        - __init__ (init_dict = d) d must be a dictionnary wiht every properties as keys

        ndarray or list can be given for Vector and Matrix
        object or dict can be given for pyleecan Object"""

        if mesh == -1:
            mesh = Mesh()
        if solution == -1:
            solution = Solution()
        if init_dict is not None:  # Initialisation by dict
            check_init_dict(init_dict, ["name", "mesh", "solution"])
            # Overwrite default value with init_dict content
            if "name" in list(init_dict.keys()):
                name = init_dict["name"]
            if "mesh" in list(init_dict.keys()):
                mesh = init_dict["mesh"]
            if "solution" in list(init_dict.keys()):
                solution = init_dict["solution"]
        # Initialisation by argument
        self.parent = None
        self.name = name
        # mesh can be None, a Mesh object or a dict
        if isinstance(mesh, dict):
            self.mesh = Mesh(init_dict=mesh)
        else:
            self.mesh = mesh
        # solution can be None, a Solution object or a dict
        if isinstance(solution, dict):
            # Check that the type is correct (including daughter)
            class_name = solution.get("__class__")
            if class_name not in ["Solution", "SolutionFEMM"]:
                raise InitUnKnowClassError("Unknow class name " + class_name +
                                           " in init_dict for solution")
            # Dynamic import to call the correct constructor
            module = __import__("pyleecan.Classes." + class_name,
                                fromlist=[class_name])
            class_obj = getattr(module, class_name)
            self.solution = class_obj(init_dict=solution)
        else:
            self.solution = solution

        # The class is frozen, for now it's impossible to add new properties
        self._freeze()

    def __str__(self):
        """Convert this objet in a readeable string (for print)"""

        MeshSolution_str = ""
        if self.parent is None:
            MeshSolution_str += "parent = None " + linesep
        else:
            MeshSolution_str += ("parent = " + str(type(self.parent)) +
                                 " object" + linesep)
        MeshSolution_str += 'name = "' + str(self.name) + '"' + linesep
        MeshSolution_str += "mesh = " + str(
            self.mesh.as_dict()) + linesep + linesep
        MeshSolution_str += "solution = " + str(self.solution.as_dict())
        return MeshSolution_str

    def __eq__(self, other):
        """Compare two objects (skip parent)"""

        if type(other) != type(self):
            return False
        if other.name != self.name:
            return False
        if other.mesh != self.mesh:
            return False
        if other.solution != self.solution:
            return False
        return True

    def as_dict(self):
        """Convert this objet in a json seriable dict (can be use in __init__)
        """

        MeshSolution_dict = dict()
        MeshSolution_dict["name"] = self.name
        if self.mesh is None:
            MeshSolution_dict["mesh"] = None
        else:
            MeshSolution_dict["mesh"] = self.mesh.as_dict()
        if self.solution is None:
            MeshSolution_dict["solution"] = None
        else:
            MeshSolution_dict["solution"] = self.solution.as_dict()
        # The class name is added to the dict fordeserialisation purpose
        MeshSolution_dict["__class__"] = "MeshSolution"
        return MeshSolution_dict

    def _set_None(self):
        """Set all the properties to None (except pyleecan object)"""

        self.name = None
        if self.mesh is not None:
            self.mesh._set_None()
        if self.solution is not None:
            self.solution._set_None()

    def _get_name(self):
        """getter of name"""
        return self._name

    def _set_name(self, value):
        """setter of name"""
        check_var("name", value, "str")
        self._name = value

    # (Optional) Descriptive name of the mesh
    # Type : str
    name = property(
        fget=_get_name,
        fset=_set_name,
        doc=u"""(Optional) Descriptive name of the mesh""",
    )

    def _get_mesh(self):
        """getter of mesh"""
        return self._mesh

    def _set_mesh(self, value):
        """setter of mesh"""
        check_var("mesh", value, "Mesh")
        self._mesh = value

        if self._mesh is not None:
            self._mesh.parent = self

    # A Mesh object.
    # Type : Mesh
    mesh = property(fget=_get_mesh, fset=_set_mesh, doc=u"""A Mesh object. """)

    def _get_solution(self):
        """getter of solution"""
        return self._solution

    def _set_solution(self, value):
        """setter of solution"""
        check_var("solution", value, "Solution")
        self._solution = value

        if self._solution is not None:
            self._solution.parent = self

    # A Solution object which are defined with respect to the mesh attribute.
    # Type : Solution
    solution = property(
        fget=_get_solution,
        fset=_set_solution,
        doc=
        u"""A Solution object which are defined with respect to the mesh attribute.""",
    )