Mod: few tests + test block

This commit is contained in:
L-Nafaryus 2021-08-02 16:36:06 +05:00
parent 96816fbca9
commit 60d4e37749
16 changed files with 187 additions and 75 deletions

View File

@ -1,12 +1,13 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from anisotropy.anisotropy import (
from anisotropy.core import (
Anisotropy,
logger
)
from anisotropy.simple import simple
from anisotropy.bodyCentered import bodyCentered
from anisotropy.faceCentered import faceCentered
from anisotropy.simple import Simple
from anisotropy.bodyCentered import BodyCentered
from anisotropy.faceCentered import FaceCentered

View File

@ -1,6 +1,6 @@
from math import pi, sqrt
class simple(object):
class BodyCentered(object):
def __init__(self, **kwargs):
self.direction = kwargs.get("direction", [1, 0, 0])
@ -13,9 +13,9 @@ class simple(object):
def build(self):
from salomepl import getGeom
import salomepl
geompy = getGeom()
geompy = salomepl.geometry.getGeom()
###
# Pore Cell

View File

@ -39,9 +39,10 @@ __version__ = "1.1"
import os
import toml
from copy import deepcopy
from anisotropy.models import db, Structure, Mesh
from anisotropy.models import db, JOIN, Structure, Mesh, SubMesh, MeshResult
from anisotropy.utils import struct, deepupdate
import salomepl
import openfoam
###
# Environment variables and config
@ -59,20 +60,22 @@ _defaultConfig = os.path.join(env["ROOT"], "anisotropy/default.toml")
if os.path.exists(_defaultConfig):
env.update(toml.load(_defaultConfig))
if os.path.exists(env["CONFIG"]):
config = toml.load(env["CONFIG"])
#if os.path.exists(env["CONFIG"]):
# config = toml.load(env["CONFIG"])
for restricted in ["ROOT", "BUILD", "LOG", "CONFIG"]:
if config.get(restricted):
config.pop(restricted)
# for restricted in ["ROOT", "BUILD", "LOG", "CONFIG"]:
# if config.get(restricted):
# config.pop(restricted)
for m, structure in enumerate(config["structures"]):
for n, estructure in enumerate(env["structures"]):
if estructure["name"] == structure["name"]:
deepupdate(env["structures"][n], config["structures"][m])
# TODO: not working if custom config empty and etc
# for m, structure in enumerate(config["structures"]):
# for n, estructure in enumerate(env["structures"]):
# if estructure["name"] == structure["name"]:
# deepupdate(env["structures"][n], config["structures"][m])
# config.pop("structures")
# deepupdate(env, config)
config.pop("structures")
deepupdate(env, config)
###
# Logger
@ -109,7 +112,7 @@ class Anisotropy(object):
self.params = []
#self.evalParameters(env)
self.setupDB()
#self.setupDB()
@staticmethod
def version():
@ -121,8 +124,8 @@ class Anisotropy(object):
}
try:
salomeplVersion = salomepl.version()
openfoamVersion = openfoam.foamVersion()
versions["Salome"] = salomepl.utils.version()
versions["OpenFOAM"] = openfoam.version()
except Exception:
pass
@ -131,6 +134,7 @@ class Anisotropy(object):
def evalEnvParameters(self):
""" 'Uncompress' and eval environment parameters """
from math import sqrt
structures = deepcopy(self.env["structures"])
@ -211,7 +215,7 @@ class Anisotropy(object):
))
def getParams(structure, direction, theta):
def getParams(structure: str, direction: list, theta: float):
for entry in self.params:
if entry["name"] == structure and \
entry["geometry"]["direction"] == direction and \
@ -220,7 +224,8 @@ class Anisotropy(object):
def setupDB(self):
self.db = db.init(self.env["db_path"])
self.db = db
self.db.init(self.env["db_path"])
if not os.path.exists(self.env["db_path"]):
self.db.create_tables([
@ -236,6 +241,7 @@ class Anisotropy(object):
for entry in self.params:
query = (Structure
.select()
.join(Mesh, JOIN.INNER, on = (Mesh.structure_id == Structure.id))
.where(
Structure.name == entry["name"],
Structure.direction == str(entry["geometry"]["direction"]),
@ -251,7 +257,7 @@ class Anisotropy(object):
m = deepcopy(entry["mesh"])
sm = deepcopy(entry.get("submesh", {}))
sm = deepcopy(entry.get("submesh", []))
mr = deepcopy(entry.get("meshResult", {}))
@ -262,8 +268,8 @@ class Anisotropy(object):
m.update(structure_id = stab)
mtab = Mesh.create(**m)
sm.update(mesh_id = mtab)
smtab = SubMesh.create(**sm)
for item in sm:
smtab = SubMesh.create(**item, mesh_id = mtab)
mr.update(mesh_id = mtab)
mrtab = MeshResult.create(**mr)
@ -284,13 +290,19 @@ class Anisotropy(object):
)
.execute())
(SubMesh.update(**sm)
for item in sm:
(SubMesh.update(**item)
.where(
Submesh.mesh_id == None # TODO: ???
SubMesh.mesh_id == query.get().mesh_id,
SubMesh.name == item["name"]
)
.execute())
# TODO: for MeshResult
(MeshResult.update(**mr)
.where(
MeshResult.mesh_id == query.get().mesh_id)
.execute())
@timer
def updateFromDB(self):
@ -316,7 +328,7 @@ class Anisotropy(object):
scriptpath = os.path.join(self.env["ROOT"], "anisotropy/genmesh.py")
port = 2900
out, err, returncode = salomepl.runSalome(port, scriptpath, env["ROOT"], name, direction, theta)
return salomepl.utils.runSalome(port, scriptpath, env["ROOT"], name, direction, theta)
def computeFlow(self):
pass
@ -480,7 +492,6 @@ def computeMesh(case):
import openfoam
def computeFlow(case):
###

View File

@ -56,7 +56,8 @@ faceCentered = true
# auto # faces: list
extrusionMethod = "SURF_OFFSET_SMOOTH"
[structures.submesh.strips]
[[structures.submesh]]
name = "strips"
maxSize = 0.5
minSize = 0.05
@ -124,7 +125,8 @@ faceCentered = true
# auto # faces: list
extrusionMethod = "SURF_OFFSET_SMOOTH"
[structures.submesh.strips]
[[structures.submesh]]
name = "strips"
maxSize = 0.5
minSize = 0.05
@ -192,7 +194,8 @@ faceCentered = true
# auto # faces: list
extrusionMethod = "SURF_OFFSET_SMOOTH"
[structures.submesh.strips]
[[structures.submesh]]
name = "strips"
maxSize = 0.5
minSize = 0.05

View File

@ -1,6 +1,6 @@
from math import pi, sqrt
class faceCentered(object):
class FaceCentered(object):
def __init__(self, **kwargs):
self.direction = kwargs.get("direction", [1, 0, 0])
@ -13,9 +13,9 @@ class faceCentered(object):
def build(self):
from salomepl import getGeom
import salomepl
geompy = getGeom()
geompy = salomepl.geometry.getGeom()
###
# Pore Cell

View File

@ -15,6 +15,10 @@ import click
@click.argument("direction")
@click.argument("theta", type = click.FLOAT)
def genmesh(root, name, direction, theta):
print(root)
print(name)
print(direction)
print(theta)
###
# Args
##
@ -37,13 +41,7 @@ def genmesh(root, name, direction, theta):
faceCentered
)
from salomepl.geometry import getGeom
from salomepl.mesh import (
Mesh,
Fineness,
ExtrusionMethod,
defaultParameters
)
import salomepl
###
# Model
@ -71,7 +69,7 @@ def genmesh(root, name, direction, theta):
###
# Shape
##
geompy = getGeom()
geompy = salomepl.geometry.getGeom()
structure = locals().get(p["name"])
shape, groups = structure(**p["geometry"])
@ -104,7 +102,7 @@ def genmesh(root, name, direction, theta):
faces.append(group)
mesh = Mesh(shape)
mesh = salomepl.mesh.Mesh(shape)
mesh.Tetrahedron(**mp)
if mp["viscousLayers"]:
@ -112,16 +110,16 @@ def genmesh(root, name, direction, theta):
smp = p["submesh"]
for name in smp.keys():
for submesh in smp:
for group in groups:
if group.GetName() == name:
if submesh["name"] == group.GetName():
subshape = group
smp["maxSize"] = meanSize * 1e-1
smp["minSize"] = meanSize * 1e-3
smp["chordalError"] = smp["minSize"] * 1e+1
submesh["maxSize"] = meanSize * 1e-1
submesh["minSize"] = meanSize * 1e-3
submesh["chordalError"] = submesh["minSize"] * 1e+1
mesh.Triangle(subshape, **smp)
mesh.Triangle(subshape, **submesh)
model.updateDB()
@ -154,3 +152,4 @@ def genmesh(root, name, direction, theta):
salome.salome_close()
genmesh()

View File

@ -77,8 +77,27 @@ class Mesh(BaseModel):
extrusionMethod = TextField(null = True)
class SubMesh(Mesh):
class SubMesh(BaseModel):
mesh_id = ForeignKeyField(Mesh, backref = "submeshes")
name = TextField()
maxSize = FloatField(null = True)
minSize = FloatField(null = True)
fineness = IntegerField(null = True)
growthRate = FloatField(null = True)
nbSegPerEdge = FloatField(null = True)
nbSegPerRadius = FloatField(null = True)
chordalErrorEnabled = BooleanField(null = True)
chordalError = FloatField(null = True)
secondOrder = BooleanField(null = True)
optimize = BooleanField(null = True)
quadAllowed = BooleanField(null = True)
useSurfaceCurvature = BooleanField(null = True)
fuseEdges = BooleanField(null = True)
checkChartBoundary = BooleanField(null = True)
class MeshResult(BaseModel):

View File

@ -1,6 +1,6 @@
from math import pi, sqrt
class simple(object):
class Simple(object):
def __init__(self, **kwargs):
self.direction = kwargs.get("direction", [1, 0, 0])
@ -13,9 +13,9 @@ class simple(object):
def build(self):
from salomepl import getGeom
import salomepl
geompy = getGeom()
geompy = salomepl.geometry.getGeom()
###
# Pore Cell

View File

@ -4,7 +4,7 @@ from .meshManipulation import createPatch, transformPoints, checkMesh, renumberM
from .miscellaneous import foamDictionary
from .parallelProcessing import decomposePar
from .solvers import potentialFoam, simpleFoam
from .utils import foamVersion, foamClean, uniform
from .utils import version, foamClean, uniform
__all__ = [
# meshConversion
@ -27,7 +27,7 @@ __all__ = [
"simpleFoam",
# utils
"foamVersion",
"version",
"foamClean",
"uniform"
]

View File

@ -1,8 +1,8 @@
import os
import shutil
def foamVersion() -> str:
return "OpenFOAM-{}".format(os.environ["WM_PROJECT_VERSION"])
def version() -> str:
return os.environ["WM_PROJECT_VERSION"]
def foamClean(case: str = None):

View File

@ -0,0 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from salomepl import (
geometry,
mesh,
utils
)

View File

@ -1,8 +1,16 @@
try:
import GEOM
from salome.geom import geomBuilder
except ImportError:
print("[Warning] Trying to get SALOME geometry modules outside SALOME environment. Modules won't be imported.")
if globals().get("geomBuilder"):
geompy = geomBuilder.New()
else:
geompy = None
def getGeom():
return geompy

View File

@ -1,7 +1,16 @@
try:
import SMESH
from salome.smesh import smeshBuilder
except ImportError:
print("[Warning] Trying to get SALOME mesh modules outside SALOME environment. Modules won't be imported.")
if globals().get("smeshBuilder"):
smesh = smeshBuilder.New()
else:
smesh = None
import enum
class Fineness(enum.Enum):
@ -13,9 +22,10 @@ class Fineness(enum.Enum):
Custom = 5
class ExtrusionMethod(object):
SURF_OFFSET_SMOOTH = smeshBuilder.SURF_OFFSET_SMOOTH
FACE_OFFSET = smeshBuilder.FACE_OFFSET
NODE_OFFSET = smeshBuilder.NODE_OFFSET
pass
#SURF_OFFSET_SMOOTH = smeshBuilder.SURF_OFFSET_SMOOTH
#FACE_OFFSET = smeshBuilder.FACE_OFFSET
#NODE_OFFSET = smeshBuilder.NODE_OFFSET
def getSmesh():
return smesh
@ -108,7 +118,7 @@ class Mesh(object):
stretchFactor = 0,
faces = [],
isFacesToIgnore = True,
extrMethod = ExtrusionMethod.SURF_OFFSET_SMOOTH,
extrMethod = None,#ExtrusionMethod.SURF_OFFSET_SMOOTH,
**kwargs
):

View File

@ -32,7 +32,7 @@ def version() -> str:
def runSalome(port: int, scriptpath: str, root: str, logpath: str = None, *args) -> int:
if os.environ.get("SALOME_PATH"):
cmd = os.path.join(os.environ["SALOME_PATH"], salome)
cmd = [ os.path.join(os.environ["SALOME_PATH"], "salome") ]
else:
raise(SalomeNotFound("Can't find salome executable."))
@ -51,8 +51,10 @@ def runSalome(port: int, scriptpath: str, root: str, logpath: str = None, *args)
fmtargs
]
cmd.extend(cmdargs)
with subprocess.Popen(
[ cmd, cmdargs ],
cmd,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
) as proc, open(logpath, "wb") as logfile:
@ -61,7 +63,7 @@ def runSalome(port: int, scriptpath: str, root: str, logpath: str = None, *args)
for line in proc.stdout:
logfile.write(line)
out, err = p.communicate()
out, err = proc.communicate()
if err:
logfile.write(err)

34
simple Normal file
View File

@ -0,0 +1,34 @@
runSalome running on localhost
Check if port can be used: 2900 - KO: port is busy
Searching for a free port for naming service: 2810 - OK
Searching Naming Service + found in 0.1 seconds
Searching /Registry in Naming Service + found in 0.5 seconds
Searching /Kernel/ModulCatalog in Naming Service + found in 0.5 seconds
RunStudy
Searching /Study in Naming Service + found in 0.5 seconds
Searching /Containers/elnafo/FactoryServer in Naming Service ++[1,
0,
0]
0.01
found in 1.0 seconds
Start SALOME, elapsed time : 2.7 seconds
th. 139821375270848 - Trace /volatile/salome/jenkins/workspace/Salome_master_CO7_MPI/SALOME-9.7.0-MPI-CO7/SOURCES/KERNEL/src/ModuleCatalog/SALOME_ModuleCatalog_Server.cxx [98] : Module Catalog Server: Naming Service was found
Warning, no type found for resource "localhost", using default value "single_machine"
Traceback (most recent call last):
File "/home/nafaryus/.vault/projects/anisotropy/anisotropy/genmesh.py", line 155, in <module>
genmesh()
File "/home/nafaryus/.vault/programs/SALOME/SALOME-9.7.0-MPI/BINARIES-CO7/Python/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/nafaryus/.vault/programs/SALOME/SALOME-9.7.0-MPI/BINARIES-CO7/Python/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/nafaryus/.vault/programs/SALOME/SALOME-9.7.0-MPI/BINARIES-CO7/Python/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/nafaryus/.vault/programs/SALOME/SALOME-9.7.0-MPI/BINARIES-CO7/Python/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/nafaryus/.vault/projects/anisotropy/anisotropy/genmesh.py", line 25, in genmesh
direction = list(map(lambda num: float(num), direction[1:-1].split(",")))
File "/home/nafaryus/.vault/projects/anisotropy/anisotropy/genmesh.py", line 25, in <lambda>
direction = list(map(lambda num: float(num), direction[1:-1].split(",")))
ValueError: could not convert string to float:
ERROR:salomeContext:SystemExit 1 in method _runAppli.
th. 140195594066816 - Trace /volatile/salome/jenkins/workspace/Salome_master_CO7_MPI/SALOME-9.7.0-MPI-CO7/SOURCES/KERNEL/src/NamingService/SALOME_NamingService.cxx [1192] : Destroy_Name(): CORBA::SystemException: unable to contact the naming service

17
tests/test_anisotropy.py Normal file
View File

@ -0,0 +1,17 @@
import os
class TestAnisotropy:
def test_import(self):
import anisotropy
def test_db(self):
import anisotropy
a = anisotropy.Anisotropy()
a.setupDB()
a.evalEnvParameters()
a.updateDB()
if os.path.exists("build/anisotropy.db"):
os.remove("build/anisotropy.db")