New: renamed modules and etc

This commit is contained in:
L-Nafaryus 2021-05-26 22:02:44 +05:00
parent d4dacd2e07
commit 86f5a5264f
No known key found for this signature in database
GPG Key ID: C76D8DCD2727DBB7
17 changed files with 126 additions and 208 deletions

View File

@ -1,18 +1,14 @@
import os, sys
from collections import namedtuple
import time
import logging
from datetime import timedelta
import multiprocessing
import shutil
import config
from config import logger
#from src import applogger
from src import utils
from src import salome_utils
from src import foam_utils
sys.path.append(os.path.abspath("../"))
import config
#from config import logger
#logger = config.logger
from utils import struct, checkEnv
def main():
if not os.path.exists(config.LOG):
@ -21,9 +17,6 @@ def main():
if not os.path.exists(config.BUILD):
os.makedirs(config.BUILD)
#global logger
#logger = applogger.Logger()
check = checkEnv()
if check:
@ -68,15 +61,7 @@ def main():
logger.info(f"Warnings: {logger.warnings}\tErrors: {logger.errors}")
class Task:
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
def createTasks():
#Task = namedtuple("Task", ["structure", "theta", "fillet", "direction", "export"])
tasks = []
structures = [ getattr(config, s)() for s in config.structures ]
@ -91,7 +76,7 @@ def createTasks():
"theta-{}".format(theta)
)
task = Task(
task = struct(
structure = name,
theta = theta,
fillet = structure.fillet,
@ -105,9 +90,10 @@ def createTasks():
return tasks
from salomepl.utils import runExecute
def createMesh(task):
scriptpath = os.path.join(config.ROOT, "samples/__init__.py")
scriptpath = os.path.join(config.ROOT, "salome/genmesh.py")
port = 2810
stime = time.monotonic()
@ -119,21 +105,23 @@ def createMesh(task):
os.path.join(task.export, "mesh.unv"),
config.ROOT
)
returncode = salome_utils.runExecute(port, scriptpath, *args)
returncode = runExecute(port, scriptpath, *args)
etime = time.monotonic()
logger.info("createMesh: elapsed time: {}".format(timedelta(seconds = etime - stime)))
from openfoam import openfoam
def calculate(task):
foamCase = [ "0", "constant", "system" ]
os.chdir(task.export)
foam_utils.foamClean()
openfoam.foamClean()
for d in foamCase:
shutil.copytree(
os.path.join(config.ROOT, "src/cubicFoam", d),
os.path.join(config.ROOT, "openfoam/template", d),
os.path.join(task.export, d)
)
@ -143,34 +131,36 @@ def calculate(task):
logger.critical(f"calculate: missed 'mesh.unv'")
return
_, returncode = foam_utils.ideasUnvToFoam("mesh.unv")
_, returncode = openfoam.ideasUnvToFoam("mesh.unv")
if returncode:
os.chdir(config.ROOT)
return returncode
foam_utils.createPatch(dictfile = "system/createPatchDict.symetry")
openfoam.createPatch(dictfile = "system/createPatchDict.symetry")
foam_utils.foamDictionary("constant/polyMesh/boundary", "entry0.defaultFaces.type", "wall")
foam_utils.foamDictionary("constant/polyMesh/boundary", "entry0.defaultFaces.inGroups", "1 (wall)")
openfoam.foamDictionary("constant/polyMesh/boundary", "entry0.defaultFaces.type", "wall")
openfoam.foamDictionary("constant/polyMesh/boundary", "entry0.defaultFaces.inGroups", "1 (wall)")
foam_utils.checkMesh()
openfoam.checkMesh()
scale = (1e-5, 1e-5, 1e-5)
foam_utils.transformPoints(scale)
openfoam.transformPoints(scale)
foam_utils.decomposePar()
openfoam.decomposePar()
foam_utils.renumberMesh()
openfoam.renumberMesh()
foam_utils.potentialFoam()
openfoam.potentialFoam()
for n in range(os.cpu_count()):
foam_utils.foamDictionary(f"processor{n}/0/U", "boundaryField.inlet.type", "pressureInletVelocity")
foam_utils.foamDictionary(f"processor{n}/0/U", "boundaryField.inlet.value", "uniform (0 0 0)")
openfoam.foamDictionary(f"processor{n}/0/U", "boundaryField.inlet.type", "pressureInletVelocity")
openfoam.foamDictionary(f"processor{n}/0/U", "boundaryField.inlet.value", "uniform (0 0 0)")
returncode = foam_utils.simpleFoam()
returncode, out = openfoam.simpleFoam()
if out:
logger.info(out)
os.chdir(config.ROOT)
@ -180,6 +170,7 @@ def calculate(task):
return returncode
def postprocessing(tasks):
surfaceFieldValue = {}

102
config.py
View File

@ -1,6 +1,7 @@
import os, sys
from src import applogger
from anisotropy.utils import Logger, struct
PROJECT = "anisotropy"
###
# Paths
##
@ -14,65 +15,27 @@ BUILD = os.path.join(ROOT, "build")
# Logger
##
global logger
logger = applogger.Logger()
###
# Utilities
##
class Parameters:
"""
[
"minSize",
"maxSize",
"growthRate",
"nbSegPerEdge",
"nbSegPerRadius",
"chordalErrorEnabled",
"chordalError",
"secondOrder",
"optimize",
"quadAllowed",
"useSurfaceCurvature",
"fuseEdges",
"checkChartBoundary"
]
"""
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
setattr(self, k, v)
class ViscousLayers(Parameters):
"""
[
"thickness",
"numberOfLayers",
"stretchFactor",
"isFacesToIgnore",
"facesToIgnore",
"extrusionMethod"
]
"""
pass
logger = Logger(PROJECT, os.path.join(LOG, f"{ PROJECT }.log"))
###
# Project variables
##
structures = [
#"simple",
"bodyCentered",
"faceCentered"
"simple",
#"bodyCentered",
#"faceCentered"
]
class simple:
theta = [c * 0.01 for c in range(1, 28 + 1)]
simple = struct(
theta = [0.01, 0.02], #[c * 0.01 for c in range(1, 28 + 1)],
directions = [
[1, 0, 0],
[0, 0, 1],
[1, 1, 1]
]
fillet = True
fineness = 3
parameters = Parameters(
],
fillet = True,
fineness = 3,
parameters = struct(
minSize = 0.01,
maxSize = 0.1,
growthRate = 0.5,
@ -86,8 +49,8 @@ class simple:
useSurfaceCurvature = True,
fuseEdges = True,
checkChartBoundary = False
)
viscousLayers = ViscousLayers(
),
viscousLayers = struct(
thickness = 0.005, # 0.01, 0.005 for 0.28, 0.01 for prism
numberOfLayers = 2,
stretchFactor = 1.2,
@ -95,18 +58,18 @@ class simple:
facesToIgnore = None,
extrusionMethod = None
)
)
class bodyCentered:
theta = [c * 0.01 for c in range(1, 18 + 1)]
bodyCentered = struct(
theta = [c * 0.01 for c in range(1, 18 + 1)],
directions = [
[1, 0, 0],
[0, 0, 1],
[1, 1, 1]
]
fillet = True
fineness = 3
parameters = Parameters(
],
fillet = True,
fineness = 3,
parameters = struct(
minSize = 0.005,
maxSize = 0.05,
growthRate = 0.5,
@ -120,8 +83,8 @@ class bodyCentered:
useSurfaceCurvature = True,
fuseEdges = True,
checkChartBoundary = False
)
viscousLayers = ViscousLayers(
),
viscousLayers = struct(
thickness = 0.005,
numberOfLayers = 2,
stretchFactor = 1.2,
@ -129,18 +92,18 @@ class bodyCentered:
facesToIgnore = None,
extrusionMethod = None
)
)
class faceCentered:
theta = [0.06, 0.13] #[c * 0.01 for c in range(1, 13 + 1)]
faceCentered = struct(
theta = [0.06, 0.13], #[c * 0.01 for c in range(1, 13 + 1)]
directions = [
#[1, 0, 0],
#[0, 0, 1],
[1, 1, 1]
]
fillet = True
fineness = 3
parameters = Parameters(
],
fillet = True,
fineness = 3,
parameters = struct(
minSize = 0.005,
maxSize = 0.05,
growthRate = 0.5,
@ -154,8 +117,8 @@ class faceCentered:
useSurfaceCurvature = True,
fuseEdges = True,
checkChartBoundary = False
)
viscousLayers = ViscousLayers(
),
viscousLayers = struct(
thickness = 0.001, # Failing on 0.13-111
numberOfLayers = 2,
stretchFactor = 1.2,
@ -163,3 +126,4 @@ class faceCentered:
facesToIgnore = None,
extrusionMethod = None
)
)

View File

@ -1,3 +1,4 @@
import re
def createPatch(dictfile: str = None, case: str = None):
args = ["-overwrite"]
@ -16,6 +17,7 @@ def transformPoints(scale: tuple, case: str = None):
def checkMesh(case: str = None):
application("checkMesh", "-allGeometry", "-allTopology", case = case, stderr = True)
out = ""
with open("checkMesh.log", "r") as io:
warnings = []
@ -24,7 +26,9 @@ def checkMesh(case: str = None):
warnings.append(line.replace("***", "").strip())
if warnings:
logger.warning("checkMesh:\n\t{}".format("\n\t".join(warnings)))
out = "checkMesh:\n\t{}".format("\n\t".join(warnings))
return out
def renumberMesh(case: str = None):

View File

@ -1,11 +1,16 @@
import os, sys, shutil
import os, sys
import subprocess
import logging
import time
import re
from datetime import timedelta
sys.path.append(os.path.abspath("../"))
from config import logger
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 = []
@ -47,79 +52,3 @@ def application(name: str, *args: str, case: str = None, stderr: bool = True, us
return out, p.returncode
def foamVersion() -> str:
return "OpenFOAM-{}".format(os.environ["WM_PROJECT_VERSION"])
def foamClean(case: str = None):
rmDirs = ["0", "constant", "system", "postProcessing", "logs"]
rmDirs.extend([ "processor{}".format(n) for n in range(os.cpu_count()) ])
path = case if case else ""
for d in rmDirs:
if os.path.exists(os.path.join(path, d)):
shutil.rmtree(os.path.join(path, d))
def ideasUnvToFoam(mesh: str, case: str = None) -> (str, int):
return application("ideasUnvToFoam", mesh, case = case, stderr = True)
def createPatch(dictfile: str = None, case: str = None):
args = ["-overwrite"]
if dictfile:
args.extend(["-dict", dictfile])
application("createPatch", *args, case = case, stderr = True)
def transformPoints(scale: tuple, case: str = None):
scale_ = "{}".format(scale).replace(",", "")
application("transformPoints", "-scale", scale_, case = case, stderr = True)
def checkMesh(case: str = None):
application("checkMesh", "-allGeometry", "-allTopology", case = case, stderr = True)
with open("checkMesh.log", "r") as io:
warnings = []
for line in io:
if re.search("\*\*\*", line):
warnings.append(line.replace("***", "").strip())
if warnings:
logger.warning("checkMesh:\n\t{}".format("\n\t".join(warnings)))
def foamDictionary(filepath: str, entry: str, value: str = None, case: str = None):
args = [filepath, "-entry", entry]
if value:
args.extend(["-set", value])
application("foamDictionary", *args, case = case, stderr = False)
def decomposePar(case: str = None):
application("decomposePar", case = case, stderr = True)
def renumberMesh(case: str = None):
application("renumberMesh", "-parallel", "-overwrite", useMPI = True, case = case, stderr = True)
def potentialFoam(case: str = None):
application("potentialFoam", "-parallel", useMPI = True, case = case, stderr = True)
def simpleFoam(case: str = None):
_, returncode = application("simpleFoam", "-parallel", useMPI = True, case = case, stderr = True)
with open("simpleFoam.log", "r") as io:
for line in io:
if re.search("solution converged", line):
logger.info("simpleFoam:\n\t{}".format(line.strip()))
return returncode

View File

@ -1,3 +1,4 @@
import re
def potentialFoam(case: str = None):
application("potentialFoam", "-parallel", useMPI = True, case = case, stderr = True)
@ -5,11 +6,12 @@ def potentialFoam(case: str = None):
def simpleFoam(case: str = None):
_, returncode = application("simpleFoam", "-parallel", useMPI = True, case = case, stderr = True)
out = ""
with open("simpleFoam.log", "r") as io:
for line in io:
if re.search("solution converged", line):
logger.info("simpleFoam:\n\t{}".format(line.strip()))
out = "simpleFoam:\n\t{}".format(line.strip())
return returncode
return returncode, out

View File

@ -1,3 +1,5 @@
import os
import shutil
def foamVersion() -> str:
return "OpenFOAM-{}".format(os.environ["WM_PROJECT_VERSION"])

View File

@ -0,0 +1,2 @@
numpy
pyquaternion

24
salomepl/README.md Normal file
View File

@ -0,0 +1,24 @@
## netgen parameters
minSize
maxSize
growthRate
nbSegPerEdge
nbSegPerRadius
chordalErrorEnabled
chordalError
secondOrder
optimize
quadAllowed
useSurfaceCurvature
fuseEdges
checkChartBoundary
## viscous layers parameters
thickness
numberOfLayers
stretchFactor
isFacesToIgnore
facesToIgnore
extrusionMethod

0
salomepl/__init__.py Normal file
View File

View File

@ -1,25 +1,25 @@
###
# This file executes inside salome environment
#
# salome starts at user home directory
##
from collections import namedtuple
import os, sys
import logging
from pyquaternion import Quaternion
import math
import salome
# get project path from args
sys.path.append(sys.argv[6])
import config
from config import logger
#from src import applogger
from simple import simpleCubic, simpleHexagonalPrism
from faceCentered import faceCenteredCubic, faceCenteredHexagonalPrism
from bodyCentered import bodyCenteredCubic, bodyCenteredHexagonalPrism
from src import geometry_utils
from src import mesh_utils
from salomepl.simple import simpleCubic, simpleHexagonalPrism
from salomepl.faceCentered import faceCenteredCubic, faceCenteredHexagonalPrism
from salomepl.bodyCentered import bodyCenteredCubic, bodyCenteredHexagonalPrism
from salomepl.geometry import getGeom
from salomepl.mesh import smeshBuilder, meshCreate, meshCompute, meshStats, meshExport
def main():
@ -30,10 +30,10 @@ def main():
flowdirection = [int(coord) for coord in sys.argv[4]]
export = str(sys.argv[5])
genMesh(stype, theta, fillet, flowdirection, export)
genmesh(stype, theta, fillet, flowdirection, export)
def genMesh(stype, theta, fillet, direction, export):
def genmesh(stype, theta, fillet, direction, export):
logger.info("""genMesh:
structure type:\t{}
@ -85,7 +85,7 @@ def genMesh(stype, theta, fillet, direction, export):
###
# Shape
##
geompy = geometry_utils.getGeom()
geompy = getGeom()
shape, groups = structure(*params)
[length, surfaceArea, volume] = geompy.BasicProperties(shape, theTolerance = 1e-06)
@ -103,13 +103,13 @@ def genMesh(stype, theta, fillet, direction, export):
facesToIgnore.append(group)
viscousLayers.facesToIgnore = facesToIgnore
viscousLayers.extrusionMethod = mesh_utils.smeshBuilder.SURF_OFFSET_SMOOTH
viscousLayers.extrusionMethod = smeshBuilder.SURF_OFFSET_SMOOTH
mesh = mesh_utils.meshCreate(shape, groups, fineness, parameters, viscousLayers)
mesh_utils.meshCompute(mesh)
mesh = meshCreate(shape, groups, fineness, parameters, viscousLayers)
meshCompute(mesh)
mesh_utils.meshStats(mesh)
mesh_utils.meshExport(mesh, export)
meshStats(mesh)
meshExport(mesh, export)
salome.salome_close()

View File

@ -1,9 +1,9 @@
import GEOM
from salome.geom import geomBuilder
geompy = geomBuilder.New()
import math
import logging
from pyquaternion import Quaternion
import numpy as np