# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
#
"""Geof file reader (Zset mesh file)
"""
from Muscat.IO.IOFactory import RegisterReaderClass
import numpy as np
from Muscat.Types import MuscatIndex
from Muscat.Helpers.Logger import Debug, Info
import Muscat.Containers.ElementsDescription as ED
from Muscat.IO.ReaderBase import ReaderBase
from Muscat.IO.ZsetTools import GeofNumber, PermutationZSetToMuscat, nbIntegrationsPoints
[docs]def ReadGeof(fileName: str = "", string: str = "", out=None, readElset=True, readFaset=True, printNotRead=True):
"""Function API for reading a geof mesh file
Parameters
----------
fileName : str, optional
name of the file to be read, by default ""
string : str, optional
data to be read as a string instead of a file, by default ""
out : Mesh, optional
output unstructured mesh object containing reading result, by default None
readElset : bool, optional
if False, ignores the elset information, by default True
readFaset : bool, optional
if False, ignores the faset information, by default True
printNotRead : bool, optional
if True, prints in console the lines dot understood by the reader, by default True
Returns
-------
Mesh
output unstructured mesh object containing reading result
"""
reader = GeofReader()
reader.SetFileName(fileName)
reader.SetStringToRead(string)
return reader.Read(fileName=fileName, string=string, out=out, readElset=readElset, readFaset=readFaset, printNotRead=printNotRead)
[docs]class GeofReader(ReaderBase):
"""Geof Reader class"""
def __init__(self):
super().__init__()
self.commentHeader = "%"
self.readFormat = "r"
[docs] def Read(self, fileName=None, string=None, out=None, readElset=True, readFaset=True, printNotRead=True):
"""Function that performs the reading of a geof mesh file
Parameters
----------
fileName : str, optional
name of the file to be read, by default None
string : str, optional
data to be read as a string instead of a file, by default None
out : Mesh, optional
output unstructured mesh object containing reading result, by default None
readElset : bool, optional
if False, ignores the elset informations, by default True
readFaset : bool, optional
if False, ignores the faset informations, by default True
printNotRead : bool, optional
if True, prints in console the lines dot understood by the reader, by default True
Returns
-------
Mesh
output unstructured mesh object containing reading result
"""
import Muscat.Containers.Mesh as UM
if fileName is not None:
self.SetFileName(fileName)
if string is not None:
self.SetStringToRead(string)
self.StartReading()
if out is None:
res = UM.Mesh()
else:
res = out
filetointernalid = {}
FENames = {}
oidToElementContainer = {}
oidToLocalElementNumber = {}
l = self.ReadCleanLine()
while True:
# premature EOF
if l is None:
print("ERROR premature EOF: please check the integrity of your geof file") # pragma: no cover
break # pragma: no cover
# if len(l) == 0: l = string.readline().strip('\n').lstrip().rstrip(); continue
if l.startswith("**node"):
l = self.ReadCleanLine()
s = l.split()
nbNodes = int(s[0])
dim = int(s[1])
Debug("Reading " + str(nbNodes) + " Nodes in dimension " + str(dim))
res.nodes = np.empty((nbNodes, dim))
res.originalIDNodes = np.empty((nbNodes,), dtype=MuscatIndex)
cpt = 0
while True:
l = self.ReadCleanLine()
if l.startswith("**"):
break
s = l.split()
oid = int(s[0])
filetointernalid[oid] = cpt
res.originalIDNodes[cpt] = int(s[0])
res.nodes[cpt, :] = list(map(float, s[1:]))
cpt += 1
continue # pragma: no cover # unseen by coverage peephole optimization
if l.startswith("**element"):
l = self.ReadCleanLine()
nbElements = int(l.split()[0])
Info("nbElements {}".format(nbElements))
while True:
l = self.ReadCleanLine()
if l.startswith("**"):
break
s = l.split()
nametype = GeofNumber[s[1]]
conn = [filetointernalid[x] for x in map(int, s[2:])]
elements = res.GetElementsOfType(nametype)
oid = int(s[0])
if s[1] in PermutationZSetToMuscat:
conn = [conn[x] for x in PermutationZSetToMuscat[s[1]]]
cpt = elements.AddNewElement(conn, oid)
oidToElementContainer[oid] = elements
oidToLocalElementNumber[oid] = cpt - 1
if nametype not in FENames:
FENames[nametype] = []
FENames[nametype].append(s[1])
continue # pragma: no cover # unseen by coverage peephole optimization
if l.startswith("**nset"):
nsetname = l.split()[1]
Debug("nset {}".format(nsetname))
tag = res.GetNodalTag(nsetname)
while True:
l = self.ReadCleanLine()
if l.startswith("**"):
break
s = l.split()
for oid in s:
tag.AddToTag(filetointernalid[int(oid)])
continue # pragma: no cover # unseen by coverage peephole optimization
if l.startswith("**elset"):
elsetname = l.split()[1]
Debug("elset {}".format(elsetname))
while True:
l = self.ReadCleanLine()
if l.startswith("**") or readElset == False:
break # pragma: no cover # unseen by coverage peephole optimization
s = l.split()
for soid in s:
oid = int(soid)
# res.AddElementToTagUsingOriginalId(int(oid),elsetname)
oidToElementContainer[oid].tags.CreateTag(elsetname, False).AddToTag(oidToLocalElementNumber[oid])
continue # pragma: no cover # unseen by coverage peephole optimization
if l.startswith("**faset") or l.startswith("**liset"):
fasetName = l[8:]
Debug("Reading Group " + fasetName)
while True:
l = self.ReadCleanLine()
if l.startswith("**") or readFaset == False:
break # pragma: no cover # unseen by coverage peephole optimization
s = l.split()
nametype = GeofNumber[s[0]]
conn = [filetointernalid[x] for x in map(int, s[1:])]
if s[0] in PermutationZSetToMuscat:
conn = [conn[x] for x in PermutationZSetToMuscat[s[0]]]
elements = res.GetElementsOfType(nametype)
if nametype not in FENames:
FENames[nametype] = []
FENames[nametype].append(s[0])
localId = elements.AddNewElement(conn, -1)
elements.GetTag(fasetName).AddToTag(localId - 1)
continue # pragma: no cover # unseen by coverage peephole optimization
if l.startswith("***return"):
Debug("End file")
break
if l.startswith("***geometry") or l.startswith("***group"):
l = self.ReadCleanLine()
continue
# case not treated
if printNotRead == True:
Debug("line starting with <<" + l[:20] + ">> not considered in the reader")
l = self.ReadCleanLine()
continue
self.EndReading()
res.PrepareForOutput()
fenames = []
for elname in res.elements.keys():
fenames.extend(FENames[elname])
res.elemFields["FE Names"] = np.array(fenames, dtype=np.str_)
return res
RegisterReaderClass(".geof", GeofReader)
[docs]def CheckIntegrity():
data = """
***geometry
**node
5 3
1 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00
2 6.0000000000000019e-02 0.0000000000000000e+00 0.0000000000000000e+00
3 6.0000000000000012e-02 7.4999999999999928e-02 0.0000000000000000e+00
4 2.0000000000000000e-02 1.7999999999999900e-02 3.0000000000000000e-02
5 3.0000000000000019e-02 0.0000000000000000e+00 0.0200000000000000e+00
**element
1
1 c3d4 1 2 3 4
***group
**nset g1
1 2 3
**elset g2
1
**faset tri
t3 1 2 3
**faset quads
quad 1 2 5
**not treated
***return
"""
res = ReadGeof(string=data)
print(res)
from Muscat.Helpers.IO.FileTools import WriteTempFile
newFileName = WriteTempFile(filename="GeofFileTest.geof", content=data)
import Muscat.Containers.Mesh as UM
mesh = ReadGeof(fileName=newFileName, out=UM.Mesh())
np.testing.assert_equal(mesh.elemFields["FE Names"].shape[0], mesh.GetNumberOfElements())
print(mesh.elemFields["FE Names"])
print(ReadMetaData(fileName=newFileName))
return "ok"
if __name__ == "__main__":
print(CheckIntegrity()) # pragma: no cover