Working version

New: openfoam as package
Mod: logging
Fix: checking environment
New: virtual environment for python
This commit is contained in:
L-Nafaryus 2021-05-31 17:12:31 +05:00
parent ab0bf8f146
commit 4c18dc1b33
13 changed files with 152 additions and 95 deletions

1
.gitignore vendored
View File

@ -2,6 +2,7 @@ __pycache__
build/
logs/
storage/
env/
*.gz
*.xz
*.fls

View File

@ -4,6 +4,15 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ "$1" = "clean" ]; then
git clean -fdx
exit 0
fi
python ${DIR}/anisotropy/anisotropy.py
elif [ "$1" = "init" ]; then
python -m venv env
source env/bin/activate
python -m pip install --upgrade pip
python -m pip install requirements.txt
elif [ "$1" = "run" ]; then
source ${OPENFOAM}
python ${DIR}/anisotropy/anisotropy.py
fi

View File

@ -3,38 +3,39 @@ import time
from datetime import timedelta
import shutil
sys.path.append(os.path.abspath("../"))
ROOT = "/".join(__file__.split("/")[:-2])
sys.path.append(os.path.abspath(ROOT))
from utils import struct, checkEnv
from utils import struct
import toml
import logging
CONFIG = os.path.abspath("../conf/config.toml")
CONFIG = os.path.join(ROOT, "conf/config.toml")
config = struct(toml.load(CONFIG))
def main():
#CONFIG = os.path.abspath("../conf/config.toml")
#config = struct(toml.load(CONFIG))
LOG = os.path.abspath("../logs")
if not os.path.exists(LOG):
os.makedirs(LOG)
LOG = os.path.join(ROOT, "logs")
if not os.path.exists(LOG):
os.makedirs(LOG)
BUILD = os.path.abspath("../build")
if not os.path.exists(BUILD):
os.makedirs(BUILD)
BUILD = os.path.join(ROOT, "build")
if not os.path.exists(BUILD):
os.makedirs(BUILD)
logging.basicConfig(
level = logging.INFO,
format = config.logger.format,
handlers = [
logging.StreamHandler(),
logging.FileHandler(f"{ LOG }/{ config.logger.name }.log")
]
)
logger = logging.getLogger(config.logger.name)
logging.basicConfig(
level = logging.INFO,
format = config.logger.format,
handlers = [
logging.StreamHandler(),
logging.FileHandler(f"{ LOG }/{ config.logger.name }.log")
]
)
logger = logging.getLogger(config.logger.name)
def main():
if checkEnv():
return
@ -64,7 +65,7 @@ def main():
if not returncode:
task.flow = True
with open(os.path.join(config.LOG, "tasks.log"), "a") as io:
with open(os.path.join(LOG, "tasks.log"), "a") as io:
idx = tasks.index(task)
io.write(f"""Task {idx}:
structure:\t{task.structure}
@ -74,7 +75,7 @@ def main():
flow:\t{task.flow}\n""")
logger.info(f"Warnings: {logger.warnings}\tErrors: {logger.errors}")
#logger.info(f"Warnings: {logger.warnings}\tErrors: {logger.errors}")
def createTasks():
@ -89,7 +90,7 @@ def createTasks():
theta = theta,
fillet = getattr(config, structure).geometry.fillet,
direction = direction,
export = os.path.abspath(f"../build/{ structure }/direction-{ direction[0] }{ direction [1] }{ direction [2] }/theta-{ theta }"),
export = os.path.join(ROOT, f"{ BUILD }/{ structure }/direction-{ direction[0] }{ direction [1] }{ direction [2] }/theta-{ theta }"),
mesh = False,
flow = False
)
@ -98,10 +99,10 @@ def createTasks():
return tasks
from salomepl.utils import runExecute
from salomepl.utils import runExecute, salomeVersion
def createMesh(task):
scriptpath = os.path.abspath("../salomepl/genmesh.py")
scriptpath = os.path.join(ROOT, "salomepl/genmesh.py")
port = 2810
stime = time.monotonic()
@ -111,7 +112,7 @@ def createMesh(task):
int(task.fillet),
"".join([str(coord) for coord in task.direction]),
os.path.join(task.export, "mesh.unv"),
os.path.abspath("../")
ROOT
)
returncode = runExecute(port, scriptpath, *args)
@ -119,7 +120,7 @@ def createMesh(task):
logger.info("createMesh: elapsed time: {}".format(timedelta(seconds = etime - stime)))
from openfoam import openfoam
import openfoam
def calculate(task):
foamCase = [ "0", "constant", "system" ]
@ -129,7 +130,7 @@ def calculate(task):
for d in foamCase:
shutil.copytree(
os.path.abspath("../openfoam/template", d),
os.path.join(ROOT, "openfoam/template", d),
os.path.join(task.export, d)
)
@ -170,13 +171,30 @@ def calculate(task):
if out:
logger.info(out)
os.chdir(config.ROOT)
os.chdir(ROOT)
etime = time.monotonic()
logger.info("calculate: elapsed time: {}".format(timedelta(seconds = etime - stime)))
return returncode
def checkEnv():
missed = False
try:
pythonVersion = "Python {}".format(sys.version.split(" ")[0])
salomeplVersion = salomeVersion()
openfoamVersion = openfoam.foamVersion()
except Exception as e:
logger.critical("Missed environment %s", e)
missed = True
else:
logger.info(f"environment:\n\t{pythonVersion}\n\t{salomeplVersion}\n\t{openfoamVersion}")
finally:
return missed
def postprocessing(tasks):

View File

@ -150,22 +150,4 @@ def portIsFree(address, port):
return s.connect_ex((address, port)) == 0
def checkEnv():
missed = False
try:
pythonVersion = "Python {}".format(sys.version.split(" ")[0])
salomeVersion = salome_utils.salomeVersion()
foamVersion = foam_utils.foamVersion()
except Exception:
logger.critical("Missed environment")
missed = True
else:
logger.info(f"environment:\n\t{pythonVersion}\n\t{salomeVersion}\n\t{foamVersion}")
finally:
return missed

View File

@ -0,0 +1,32 @@
from .meshConversion import ideasUnvToFoam
from .meshManipulation import createPatch, transformPoints, checkMesh, renumberMesh
from .miscellaneous import foamDictionary
from .parallelProcessing import decomposePar
from .solvers import potentialFoam, simpleFoam
from .utils import foamVersion, foamClean
__all__ = [
# meshConversion
"ideasUnvToFoam",
# meshManipulation
"createPatch",
"transformPoints",
"checkMesh",
"renumberMesh",
# miscellaneous
"foamDictionary",
# parallelProcessing
"decomposePar",
# solvers
"potentialFoam",
"simpleFoam",
# utils
"foamVersion",
"foamClean"
]

View File

@ -1,17 +1,9 @@
import os, sys
import subprocess
sys.path.append(os.path.abspath("../"))
import logging
logger = logging.getLogger()
from openfoam.miscellaneous import *
from openfoam.meshConversion import *
from openfoam.meshManipulation import *
from openfoam.parallelProcessing import *
from openfoam.solvers import *
def application(name: str, *args: str, case: str = None, stderr: bool = True, useMPI: bool = False) -> int:
cmd = []

View File

@ -1,3 +1,4 @@
from .application import application
def ideasUnvToFoam(mesh: str, case: str = None) -> (str, int):
return application("ideasUnvToFoam", mesh, case = case, stderr = True)

View File

@ -1,3 +1,5 @@
from .application import application
import re
def createPatch(dictfile: str = None, case: str = None):

View File

@ -1,3 +1,4 @@
from .application import application
def foamDictionary(filepath: str, entry: str, value: str = None, case: str = None):
args = [filepath, "-entry", entry]

View File

@ -1,3 +1,4 @@
from .application import application
def decomposePar(case: str = None):
application("decomposePar", case = case, stderr = True)

View File

@ -1,3 +1,5 @@
from .application import application
import re
def potentialFoam(case: str = None):

View File

@ -9,15 +9,28 @@ import math
import salome
# get project path from args
sys.path.append(sys.argv[6])
ROOT = sys.argv[6]
sys.path.append(ROOT)
# site-packages from virtual env
sys.path.append(os.path.join(ROOT, "env/lib/python3.9/site-packages"))
import toml
import logging
from anisotropy.utils import struct
CONFIG = os.path.abspath("../conf/config.toml")
CONFIG = os.path.join(ROOT, "conf/config.toml")
config = struct(toml.load(CONFIG))
LOG = os.path.join(ROOT, "logs")
logging.basicConfig(
level = logging.INFO,
format = config.logger.format,
handlers = [
logging.StreamHandler(),
logging.FileHandler(f"{ LOG }/{ config.logger.name }.log")
]
)
logger = logging.getLogger(config.logger.name)
from salomepl.simple import simpleCubic, simpleHexagonalPrism
@ -62,9 +75,10 @@ def genmesh(stype, theta, fillet, direction, export):
elif direction == [1, 1, 1]:
structure = simpleHexagonalPrism
fineness = config.simple.fineness
parameters = config.simple.parameters
viscousLayers = config.simple.viscousLayers
#fineness = config.simple.fineness
#parameters = config.simple.parameters
#viscousLayers = config.simple.viscousLayers
meshParameters = config.simple.mesh
elif stype == "faceCentered":
if direction in [[1, 0, 0], [0, 0, 1]]:
@ -73,9 +87,10 @@ def genmesh(stype, theta, fillet, direction, export):
elif direction == [1, 1, 1]:
structure = faceCenteredHexagonalPrism
fineness = config.faceCentered.fineness
parameters = config.faceCentered.parameters
viscousLayers = config.faceCentered.viscousLayers
#fineness = config.faceCentered.fineness
#parameters = config.faceCentered.parameters
#viscousLayers = config.faceCentered.viscousLayers
meshParameters = config.faceCentered.mesh
elif stype == "bodyCentered":
if direction in [[1, 0, 0], [0, 0, 1]]:
@ -84,9 +99,10 @@ def genmesh(stype, theta, fillet, direction, export):
elif direction == [1, 1, 1]:
structure = bodyCenteredHexagonalPrism
fineness = config.bodyCentered.fineness
parameters = config.bodyCentered.parameters
viscousLayers = config.bodyCentered.viscousLayers
#fineness = config.bodyCentered.fineness
#parameters = config.bodyCentered.parameters
#viscousLayers = config.bodyCentered.viscousLayers
meshParameters = config.bodyCentered.mesh
###
# Shape
@ -108,10 +124,10 @@ def genmesh(stype, theta, fillet, direction, export):
if group.GetName() in ["inlet", "outlet"]:
facesToIgnore.append(group)
viscousLayers.facesToIgnore = facesToIgnore
viscousLayers.extrusionMethod = smeshBuilder.SURF_OFFSET_SMOOTH
meshParameters.facesToIgnore = facesToIgnore
meshParameters.extrusionMethod = smeshBuilder.SURF_OFFSET_SMOOTH
mesh = meshCreate(shape, groups, fineness, parameters, viscousLayers)
mesh = meshCreate(shape, groups, meshParameters) #fineness, parameters, viscousLayers)
meshCompute(mesh)
meshStats(mesh)

View File

@ -3,13 +3,13 @@ from salome.smesh import smeshBuilder
smesh = smeshBuilder.New()
import logging
logger = logging.getLogger(config.logger.name)
logger = logging.getLogger("anisotropy")
def getSmesh():
return smesh
def meshCreate(shape, groups, fineness, parameters, viscousLayers = None):
def meshCreate(shape, groups, parameters): #fineness, parameters, viscousLayers = None):
"""
Creates a mesh from a geometry.
@ -36,7 +36,7 @@ def meshCreate(shape, groups, fineness, parameters, viscousLayers = None):
3: "Fine",
4: "Very fine",
5: "Custom"
}[fineness]
}[parameters.fineness]
# Mesh
mesh = smesh.Mesh(shape)
@ -46,9 +46,9 @@ def meshCreate(shape, groups, fineness, parameters, viscousLayers = None):
param = netgen.Parameters()
param.SetMinSize(parameters.minSize)
param.SetMaxSize(parameters.maxSize)
param.SetFineness(fineness)
param.SetFineness(parameters.fineness)
if fineness == 5:
if parameters.fineness == 5:
param.SetGrowthRate(parameters.growthRate)
param.SetNbSegPerEdge(parameters.nbSegPerEdge)
param.SetNbSegPerRadius(parameters.nbSegPerRadius)
@ -94,30 +94,30 @@ def meshCreate(shape, groups, fineness, parameters, viscousLayers = None):
###
# Viscous layers
##
if not viscousLayers is None:
vlayer = netgen.ViscousLayers(
viscousLayers.thickness,
viscousLayers.numberOfLayers,
viscousLayers.stretchFactor,
viscousLayers.facesToIgnore,
viscousLayers.isFacesToIgnore,
viscousLayers.extrusionMethod
)
#if not viscousLayers is None:
vlayer = netgen.ViscousLayers(
parameters.thickness,
parameters.numberOfLayers,
parameters.stretchFactor,
parameters.facesToIgnore,
parameters.isFacesToIgnore,
parameters.extrusionMethod
)
logger.info("""meshCreate:
viscous layers:
thickness:\t{}
number:\t{}
stretch factor:\t{}""".format(
viscousLayers.thickness,
viscousLayers.numberOfLayers,
viscousLayers.stretchFactor))
logger.info("""meshCreate:
viscous layers:
thickness:\t{}
number:\t{}
stretch factor:\t{}""".format(
parameters.thickness,
parameters.numberOfLayers,
parameters.stretchFactor))
else:
logger.info("""meshCreate:
viscous layers: disabled""")
#else:
# logger.info("""meshCreate:
#viscous layers: disabled""")
return mesh