Working mesh creation + calculations for [1, 0, 0] and [0, 0, 1]
This commit is contained in:
parent
89dd850ab8
commit
c5cc6d0549
19
README.md
19
README.md
@ -14,20 +14,17 @@ $ git clone git@github.com:L-Nafaryus/anisotrope-cube.git
|
||||
$ cd anisotrope-cube
|
||||
```
|
||||
|
||||
* Run single structure via SALOME GUI:
|
||||
```bash
|
||||
$ salome
|
||||
|
||||
python> exec(open("PATH/simpleCubic.py").read("rb"), args=("", 0.1, "001"))
|
||||
```
|
||||
where `PATH` is a full path to `anisotrope-cube/src/`.
|
||||
|
||||
* Generate all structures with configured parameters:
|
||||
```bash
|
||||
$ python src/genmesh.py
|
||||
$ python run.py mesh
|
||||
```
|
||||
|
||||
* All meshes + calculations:
|
||||
* Run calculations:
|
||||
```bash
|
||||
$ ./build.sh
|
||||
$ python run.py calc
|
||||
```
|
||||
|
||||
* All:
|
||||
```bash
|
||||
$ python run.py all
|
||||
```
|
||||
|
324
run.py
Executable file → Normal file
324
run.py
Executable file → Normal file
@ -4,6 +4,7 @@ import time
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
import multiprocessing
|
||||
import shutil
|
||||
|
||||
ROOT = os.getcwd()
|
||||
sys.path.append(ROOT)
|
||||
@ -13,45 +14,9 @@ BUILD = os.path.join(ROOT, "build")
|
||||
|
||||
from src import utils
|
||||
from src import salome_utils
|
||||
from src import foam_utils
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_time = time.monotonic()
|
||||
logging.info("Started at {}".format(timedelta(seconds=start_time)))
|
||||
|
||||
if not os.path.exists(LOG):
|
||||
os.makedirs(LOG)
|
||||
|
||||
if not os.path.exists(BUILD):
|
||||
os.makedirs(BUILD)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/cubic.log".format(LOG))
|
||||
])
|
||||
|
||||
nprocs = os.cpu_count()
|
||||
port = 2810
|
||||
salomeServers = []
|
||||
salomeServer = namedtuple("salomeServer", ["process", "port"])
|
||||
|
||||
for n in range(nprocs):
|
||||
while not utils.portIsFree:
|
||||
port += 1
|
||||
|
||||
p = multiprocessing.Process(target = salome_utils.startServer, args = (port,))
|
||||
#s = salomeServer(salome_utils.startServer(port), port)
|
||||
s = salomeServer(p, port)
|
||||
|
||||
salomeServers.append(s)
|
||||
port += 1
|
||||
|
||||
var = []
|
||||
|
||||
# TODO: pass it to samples in namedtuples
|
||||
# get sample.directions and etc ..
|
||||
def createTasks():
|
||||
structures = [
|
||||
"simpleCubic",
|
||||
"bodyCenteredCubic",
|
||||
@ -63,13 +28,7 @@ if __name__ == "__main__":
|
||||
#[1, 1, 1]
|
||||
]
|
||||
|
||||
cmd = """python -c
|
||||
\"import sys;
|
||||
sys.append('{}');
|
||||
import samples;
|
||||
samples.genMesh('{}', {}, {}, '{}');
|
||||
\"
|
||||
""".replace("\n", "")
|
||||
Task = namedtuple("Task", ["structure", "coeff", "direction", "saveto"])
|
||||
tasks = []
|
||||
|
||||
for structure in structures:
|
||||
@ -84,181 +43,144 @@ if __name__ == "__main__":
|
||||
|
||||
for coeff in theta:
|
||||
for direction in directions:
|
||||
tasks.append(cmd.format(ROOT, structure, coeff, direction, BUILD))
|
||||
saveto = os.path.join(BUILD, structure, "coeff-{}".format(coeff),
|
||||
"direction-{}{}{}".format(direction[0], direction[1], direction[2]))
|
||||
|
||||
logging.info("tasks: {}".format(tasks))
|
||||
n = 0
|
||||
for cmd in tasks:
|
||||
var.append((salomeServer[n].port, cmd))
|
||||
n = n + 1 if n < 3 else 0
|
||||
if not os.path.exists(saveto):
|
||||
os.makedirs(saveto)
|
||||
|
||||
t = Task(structure, coeff, direction, saveto)
|
||||
tasks.append(t)
|
||||
|
||||
for s in salomeServers:
|
||||
s.process.start()
|
||||
|
||||
#res = utils.parallel(nprocs, var, salome_utils.remote)
|
||||
#print(res)
|
||||
|
||||
#for s in salomeServers:
|
||||
# s.process.join()
|
||||
return tasks
|
||||
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"""
|
||||
if __name__ == "__main__":
|
||||
###
|
||||
# SALOME
|
||||
#
|
||||
# Get main paths
|
||||
project = os.getcwd()
|
||||
src = os.path.join(project, "src")
|
||||
build = os.path.join(project, "build")
|
||||
|
||||
if not os.path.exists(build):
|
||||
os.makedirs(build)
|
||||
|
||||
# Logger
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/genmesh.log".format(build))
|
||||
])
|
||||
start_time = time.monotonic()
|
||||
|
||||
# Start in parallel
|
||||
processes = []
|
||||
structures = ["simpleCubic", "faceCenteredCubic", "bodyCenteredCubic"]
|
||||
directions = ["001"] #, "100", "111"]
|
||||
coefficients = [0.1] #[ alpha * 0.01 for alpha in range(1, 13 + 1) ]
|
||||
def createMesh(tasks):
|
||||
scriptpath = os.path.join(ROOT, "samples/__init__.py")
|
||||
port = 2810
|
||||
|
||||
for structure in structures:
|
||||
for direction in directions:
|
||||
for coefficient in coefficients:
|
||||
src_path = os.path.join(src, "{}.py".format(structure))
|
||||
build_path = os.path.join(build,
|
||||
structure,
|
||||
"direction-{}".format(direction),
|
||||
"alpha-{}".format(coefficient))
|
||||
|
||||
if not os.path.exists(build_path):
|
||||
os.makedirs(build_path)
|
||||
|
||||
p = multiprocessing.Process(target = salome,
|
||||
args = (port, src_path, build_path, coefficient, direction))
|
||||
processes.append(p)
|
||||
p.start()
|
||||
logging.info("{} on port {}.".format(p, port))
|
||||
port += 1
|
||||
|
||||
for process in processes:
|
||||
process.join()
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
|
||||
for task in tasks:
|
||||
returncode = salome_utils.runExecute(port, scriptpath, task.structure, task.coeff, "".join([str(coord) for coord in task.direction]), os.path.join(task.saveto, "mesh.unv"))
|
||||
|
||||
logging.info("Return code: {}".format(returncode))
|
||||
|
||||
if returncode == 1:
|
||||
break
|
||||
|
||||
###
|
||||
# FOAM
|
||||
#
|
||||
# Get main paths
|
||||
project = os.getcwd()
|
||||
src = os.path.join(project, "src")
|
||||
build = os.path.join(project, "build")
|
||||
|
||||
if not os.path.exists(build):
|
||||
os.makedirs(build)
|
||||
|
||||
# Logger
|
||||
def calculate(tasks):
|
||||
foamCase = [ "0", "constant", "system" ]
|
||||
rmDirs = ["0", "constant", "system", "postProcessing", "logs"] + [ "processor{}".format(n) for n in range(4)]
|
||||
fancyline = "--------------------------------------------------------------------------------"
|
||||
|
||||
for task in tasks:
|
||||
|
||||
for d in rmDirs:
|
||||
if os.path.exists(os.path.join(task.saveto, d)):
|
||||
shutil.rmtree(os.path.join(task.saveto, d))
|
||||
|
||||
for d in foamCase:
|
||||
if not os.path.exists(os.path.join(task.saveto, d)):
|
||||
shutil.copytree(os.path.join(ROOT, "src/cubicFoam", d),
|
||||
os.path.join(task.saveto, d))
|
||||
|
||||
os.chdir(task.saveto)
|
||||
casepath = "."
|
||||
|
||||
logging.info(fancyline)
|
||||
logging.info("""Args:
|
||||
structure type:\t{}
|
||||
coefficient:\t{}
|
||||
flow direction:\t{}
|
||||
path:\t{}\n""".format(task.structure, task.coeff, task.direction, task.saveto))
|
||||
|
||||
foam_utils.ideasUnvToFoam(casepath, "mesh.unv")
|
||||
|
||||
if not task.direction == [1, 1, 1]:
|
||||
shutil.copy(os.path.join(task.saveto, "system/createPatchDict.symetry"),
|
||||
os.path.join(task.saveto, "system/createPatchDict"))
|
||||
logging.info("""createPatch:
|
||||
file:\tcreatePatchDict.symetry""")
|
||||
|
||||
else:
|
||||
shutil.copy(os.path.join(task.saveto, "system/createPatchDict.cyclic"),
|
||||
os.path.join(task.saveto, "system/createPatchDict"))
|
||||
logging.info("""createPatch:
|
||||
file:\tcreatePatchDict.cyclic""")
|
||||
|
||||
foam_utils.createPatch(casepath)
|
||||
|
||||
scale = (1e-5, 1e-5, 1e-5)
|
||||
foam_utils.transformPoints(casepath, "{}".format(scale).replace(",", ""))
|
||||
logging.info("""transformPoints:
|
||||
scale:\t{}""".format(scale))
|
||||
|
||||
foam_utils.checkMesh(casepath)
|
||||
|
||||
foam_utils.decomposePar(casepath)
|
||||
|
||||
foam_utils.potentialFoam(casepath)
|
||||
|
||||
for n in range(4):
|
||||
foam_utils.foamDictionarySet(casepath, "processor{}/0/U".format(n),
|
||||
"boundaryField.inlet.type", "pressureInletVelocity")
|
||||
foam_utils.foamDictionarySet(casepath, "processor{}/0/U".format(n),
|
||||
"boundaryField.inlet.value", "uniform (0 0 0)")
|
||||
|
||||
foam_utils.simpleFoam(casepath)
|
||||
|
||||
os.chdir(ROOT)
|
||||
|
||||
logging.info(fancyline)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
if not os.path.exists(LOG):
|
||||
os.makedirs(LOG)
|
||||
|
||||
if not os.path.exists(BUILD):
|
||||
os.makedirs(BUILD)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/foam.log".format(build))
|
||||
logging.FileHandler("{}/cubic.log".format(LOG))
|
||||
])
|
||||
start_time = time.monotonic()
|
||||
|
||||
# Main entry
|
||||
structures = ["simpleCubic"] #, "bc-cubic", "fc-cubic"]
|
||||
directions = ["001"] #, "100", "111"]
|
||||
coefficients = [0.1] #[ alpha * 0.01 for alpha in range(1, 13 + 1) ]
|
||||
# TODO: add force arg
|
||||
Args = namedtuple("Args", ["mesh", "calc"])
|
||||
|
||||
for structure in structures:
|
||||
for direction in directions:
|
||||
for coefficient in coefficients:
|
||||
foamCase = [ "0", "constant", "system" ]
|
||||
src_path = os.path.join(src, "{}Foam".format(structure))
|
||||
build_path = os.path.join(build,
|
||||
structure,
|
||||
"direction-{}".format(direction),
|
||||
"alpha-{}".format(coefficient))
|
||||
|
||||
|
||||
logging.info("Entry with parameters: {}, direction = {}, alpha = {}".format(structure, direction, coefficient))
|
||||
if len(sys.argv) > 1:
|
||||
action = sys.argv[1]
|
||||
|
||||
if action == "mesh":
|
||||
args = Args(True, False)
|
||||
|
||||
logging.info("Copying baseFOAM case ...")
|
||||
for d in foamCase:
|
||||
if not os.path.exists(os.path.join(build_path, d)):
|
||||
shutil.copytree(os.path.join(src_path, d),
|
||||
os.path.join(build_path, d))
|
||||
|
||||
os.chdir(build_path)
|
||||
case_path = "."
|
||||
elif action == "calc":
|
||||
args = Args(False, True)
|
||||
|
||||
logging.info("Importing mesh to foam ...")
|
||||
ideasUnvToFoam(case_path, "{}-{}-{}.unv".format(structure, direction, coefficient))
|
||||
|
||||
logging.info("Creating patches ...")
|
||||
createPatch(case_path)
|
||||
elif action == "all":
|
||||
args = Args(True, True)
|
||||
|
||||
logging.info("Scaling mesh ...")
|
||||
transformPoints(case_path, "(1e-5 1e-5 1e-5)")
|
||||
|
||||
logging.info("Checking mesh ...")
|
||||
checkMesh(case_path)
|
||||
|
||||
#logging.info("Changing mesh boundaries types ...")
|
||||
#foamDictionarySet(case_path, "constant/polyMesh/boundary", "entry0.wall.type", "wall")
|
||||
#foamDictionarySet(case_path, "constant/polyMesh/boundary", "entry0.symetryPlane.type", "symetryPlane")
|
||||
else:
|
||||
args = Args(True, True)
|
||||
|
||||
logging.info("Decomposing case ...")
|
||||
decomposePar(case_path)
|
||||
|
||||
logging.info("Evaluating initial approximation via potentialFoam ...")
|
||||
potentialFoam(case_path)
|
||||
|
||||
logging.info("Preparing boundaryFields for simpleFoam ...")
|
||||
for n in range(4):
|
||||
foamDictionarySet(case_path, "processor{}/0/U".format(n),
|
||||
"boundaryField.inlet.type", "pressureInletVelocity")
|
||||
foamDictionarySet(case_path, "processor{}/0/U",
|
||||
"boundaryField.inlet.value", "uniform (0 0 0)")
|
||||
|
||||
logging.info("Calculating ...")
|
||||
simpleFoam(case_path)
|
||||
tasks = createTasks()
|
||||
logging.info("Tasks: {}".format(len(tasks)))
|
||||
|
||||
if args.mesh:
|
||||
start_time = time.monotonic()
|
||||
logging.info("Started at {}".format(timedelta(seconds=start_time)))
|
||||
|
||||
os.chdir(project)
|
||||
createMesh(tasks)
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
|
||||
if args.calc:
|
||||
calculate(tasks)
|
||||
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
"""
|
||||
|
@ -1,14 +1,21 @@
|
||||
from .simpleCubic import simpleCubic
|
||||
from .faceCenteredCubic import faceCenteredCubic
|
||||
from .bodyCenteredCubic import bodyCenteredCubic
|
||||
from collections import namedtuple
|
||||
import os, sys
|
||||
import logging
|
||||
|
||||
ROOT = "/home/nafaryus/projects/anisotrope-cube"
|
||||
sys.path.append(ROOT)
|
||||
|
||||
LOG = os.path.join(ROOT, "logs")
|
||||
|
||||
import salome
|
||||
|
||||
from simpleCubic import simpleCubic
|
||||
from faceCenteredCubic import faceCenteredCubic
|
||||
from bodyCenteredCubic import bodyCenteredCubic
|
||||
|
||||
from src import geometry_utils
|
||||
from src import mesh_utils
|
||||
|
||||
import salome
|
||||
from collections import namedtuple
|
||||
import os
|
||||
|
||||
def genMesh(stype, theta, flowdirection, saveto):
|
||||
_G = globals()
|
||||
|
||||
@ -40,18 +47,55 @@ def genMesh(stype, theta, flowdirection, saveto):
|
||||
mesh = mesh_utils.meshCreate(geometry, boundary, fineness)
|
||||
mesh_utils.meshCompute(mesh)
|
||||
|
||||
path = os.path.join(saveto,
|
||||
stype,
|
||||
"theta-%s" % theta,
|
||||
"direction-{}{}{}".format(flowdirection[0], flowdirection[1], flowdirection[2]))
|
||||
#path = os.path.join(saveto,
|
||||
# stype,
|
||||
# "theta-%s" % theta,
|
||||
# "direction-{}{}{}".format(flowdirection[0], flowdirection[1], flowdirection[2]))
|
||||
|
||||
if not os.path.exists(path):
|
||||
logging.info("Creating directory: {}".format(path))
|
||||
os.makedirs(path)
|
||||
#if not os.path.exists(path):
|
||||
# logging.info("Creating directory: {}".format(path))
|
||||
# os.makedirs(path)
|
||||
|
||||
mesh_utils.meshExport(mesh, os.path.join(path, "mesh.unv"))
|
||||
mesh_utils.meshExport(mesh, saveto) # os.path.join(path, "mesh.unv"))
|
||||
|
||||
salome.salome_close()
|
||||
|
||||
else:
|
||||
raise Exception("Unknown sample function")
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/cubic.log".format(LOG))
|
||||
])
|
||||
|
||||
fancyline = "--------------------------------------------------------------------------------"
|
||||
logging.info(fancyline)
|
||||
|
||||
stype = str(sys.argv[1])
|
||||
theta = float(sys.argv[2])
|
||||
|
||||
#ignore = "[], "
|
||||
flowdirection = [int(coord) for coord in sys.argv[3]]
|
||||
|
||||
#for sym in str(sys.argv[3]):
|
||||
# if sym not in list(ignore):
|
||||
# flowdirection.append(int(sym))
|
||||
|
||||
saveto = str(sys.argv[4])
|
||||
|
||||
logging.info("""Args:
|
||||
structure type:\t{}
|
||||
coefficient:\t{}
|
||||
flow direction:\t{}
|
||||
export path:\t{}\n""".format(stype, theta, flowdirection, saveto))
|
||||
|
||||
#print(flowdirection)
|
||||
|
||||
genMesh(stype, theta, flowdirection, saveto)
|
||||
|
||||
logging.info(fancyline)
|
||||
|
115
src/cubicFoam/system/createPatchDict.symetry
Normal file
115
src/cubicFoam/system/createPatchDict.symetry
Normal file
@ -0,0 +1,115 @@
|
||||
/*--------------------------------*- C++ -*----------------------------------*\
|
||||
| ========= | |
|
||||
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
|
||||
| \\ / O peration | Version: v2012 |
|
||||
| \\ / A nd | Website: www.openfoam.com |
|
||||
| \\/ M anipulation | |
|
||||
\*---------------------------------------------------------------------------*/
|
||||
FoamFile
|
||||
{
|
||||
version 2.0;
|
||||
format ascii;
|
||||
class dictionary;
|
||||
object createPatchDict;
|
||||
}
|
||||
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
|
||||
|
||||
pointSync false;
|
||||
|
||||
// Patches to create.
|
||||
patches
|
||||
(
|
||||
{
|
||||
name inlet;
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type patch;
|
||||
inGroups (inlet);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (inlet_);
|
||||
}
|
||||
|
||||
{
|
||||
name outlet;
|
||||
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type patch;
|
||||
inGroups (outlet);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (outlet_);
|
||||
}
|
||||
|
||||
{
|
||||
name symetryPlaneFW;
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type symetryPlane;
|
||||
inGroups (symetryPlane);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (symetryPlaneFW_);
|
||||
}
|
||||
|
||||
{
|
||||
name symetryPlaneBW;
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type symetryPlane;
|
||||
inGroups (symetryPlane);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (symetryPlaneBW_);
|
||||
}
|
||||
|
||||
{
|
||||
name symetryPlaneL;
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type symetryPlane;
|
||||
inGroups (symetryPlane);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (symetryPlaneL_);
|
||||
}
|
||||
|
||||
{
|
||||
name symetryPlaneR;
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type symetryPlane;
|
||||
inGroups (symetryPlane);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (symetryPlaneR_);
|
||||
}
|
||||
|
||||
{
|
||||
name wall;
|
||||
|
||||
patchInfo
|
||||
{
|
||||
type wall;
|
||||
inGroups (wall);
|
||||
}
|
||||
|
||||
constructFrom patches;
|
||||
patches (wall_);
|
||||
}
|
||||
);
|
||||
|
||||
// ************************************************************************* //
|
@ -1,27 +1,43 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
import os, shutil
|
||||
import os, sys, shutil
|
||||
import subprocess
|
||||
import logging
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
def application(name, case, log=False, args=[], parallel=False):
|
||||
logging.info("Running '{}'.".format(name))
|
||||
|
||||
|
||||
if log:
|
||||
logfile = open("{}/{}.log".format(case, name), "a")
|
||||
#if log:
|
||||
# logfile = open("{}/{}.log".format(case, name), "a")
|
||||
|
||||
mpirun = []
|
||||
if parallel:
|
||||
mpirun = ["mpirun", "-np", "4", "--oversubscribe"]
|
||||
|
||||
cmd = mpirun + [name, "-case", case] + args
|
||||
logging.info("Running '{}'".format(" ".join(cmd)))
|
||||
|
||||
with subprocess.Popen(cmd,
|
||||
#shell = True,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE) as p, \
|
||||
open("{}/{}.log".format(case, name), "wb") as logfile:
|
||||
|
||||
for line in p.stdout:
|
||||
#sys.stdout.buffer.write(line)
|
||||
logfile.write(line)
|
||||
|
||||
subprocess.run(mpirun + [name, "-case", case] + args,
|
||||
stdout=logfile if log else subprocess.STDOUT,
|
||||
stderr=logfile if log else subprocess.STDOUT)
|
||||
#for line in p.stderr:
|
||||
# logfile.write(line)
|
||||
|
||||
out, err = p.communicate()
|
||||
|
||||
if err:
|
||||
logging.error("""{}:
|
||||
{}""".format(name, str(err, "utf-8")))
|
||||
|
||||
return p.returncode
|
||||
|
||||
if log:
|
||||
logfile.close()
|
||||
|
||||
def ideasUnvToFoam(case, mesh):
|
||||
application("ideasUnvToFoam", case, True, [mesh])
|
||||
|
@ -58,7 +58,10 @@ def boundaryCreate(gobj, dvec, grains):
|
||||
geompy.addToStudy(yvec, "yvec")
|
||||
geompy.addToStudy(zvec, "zvec")
|
||||
|
||||
logging.info("boundaryCreate: dvec = {}".format(dvec))
|
||||
logging.info("""boundaryCreate:
|
||||
direction vectors: x = {}
|
||||
y = {}
|
||||
z = {}""".format(dvec.x, dvec.y, dvec.z))
|
||||
|
||||
planes = geompy.ExtractShapes(gobj, geompy.ShapeType["FACE"], False)
|
||||
planes = geompy.MakeCompound(planes)
|
||||
@ -79,7 +82,7 @@ def boundaryCreate(gobj, dvec, grains):
|
||||
xang = round(geompy.GetAngle(nvec, xvec), 0)
|
||||
yang = round(geompy.GetAngle(nvec, yvec), 0)
|
||||
zang = round(geompy.GetAngle(nvec, zvec), 0)
|
||||
print(xang, yang, zang, sep="\t")
|
||||
#print(xang, yang, zang, sep="\t")
|
||||
|
||||
if xang == 0:
|
||||
inletplanes.append(plane)
|
||||
@ -98,14 +101,16 @@ def boundaryCreate(gobj, dvec, grains):
|
||||
|
||||
elif zang == 180:
|
||||
rplanes.append(plane)
|
||||
|
||||
logging.info(
|
||||
"boundaryCreate: planes = {}, inletplanes = {}, outletplanes = {}".format(
|
||||
len(planes), len(inletplanes), len(outletplanes)))
|
||||
|
||||
logging.info(
|
||||
"boundaryCreate: fwplanes = {}, bwplanes = {}, lplanes = {}, rplanes = {}".format(
|
||||
len(fwplanes), len(bwplanes), len(lplanes), len(rplanes)))
|
||||
|
||||
logging.info("""boundaryCreate:
|
||||
planes count:\t{}
|
||||
inlet planes:\t{}
|
||||
outlet planes:\t{}
|
||||
forward planes:\t{}
|
||||
backward planes:\t{}
|
||||
left planes:\t{}
|
||||
right planes:\t{}""".format(len(planes), len(inletplanes), len(outletplanes),
|
||||
len(fwplanes), len(bwplanes), len(lplanes), len(rplanes)))
|
||||
|
||||
# Main groups
|
||||
inlet = createGroup(gobj, inletplanes, grains, "inlet")
|
||||
|
@ -44,7 +44,8 @@ def meshCreate(gobj, boundary, fineness, viscousLayers=None):
|
||||
4: "Very fine"
|
||||
}[fineness]
|
||||
|
||||
logging.info("meshCreate: mesh fineness - {}".format(Fineness))
|
||||
logging.info("""meshCreate:
|
||||
mesh fineness:\t{}""".format(Fineness))
|
||||
|
||||
mesh = smesh.Mesh(gobj)
|
||||
netgen = mesh.Tetrahedron(algo=smeshBuilder.NETGEN_1D2D3D)
|
||||
@ -66,7 +67,10 @@ def meshCreate(gobj, boundary, fineness, viscousLayers=None):
|
||||
param.SetQuadAllowed( 0 )
|
||||
|
||||
if not viscousLayers is None:
|
||||
logging.info("meshCreate: viscous layers params - thickness = {}, number = {}, stretch factor = {}".format(
|
||||
logging.info("""meshCreate:
|
||||
viscous layers: thickness = {}
|
||||
number = {}
|
||||
stretch factor = {}""".format(
|
||||
viscousLayers["thickness"], viscousLayers["number"], viscousLayers["stretch"]))
|
||||
|
||||
vlayer = netgen.ViscousLayers(
|
||||
@ -77,7 +81,8 @@ def meshCreate(gobj, boundary, fineness, viscousLayers=None):
|
||||
1, smeshBuilder.NODE_OFFSET)
|
||||
|
||||
else:
|
||||
logging.info("meshCreate: viscous layers are disabled")
|
||||
logging.info("""meshCreate:
|
||||
viscous layers: disabled""")
|
||||
|
||||
for name, b in boundary.items():
|
||||
mesh.GroupOnGeom(b, "{}_".format(name), SMESH.FACE)
|
||||
@ -87,12 +92,16 @@ def meshCreate(gobj, boundary, fineness, viscousLayers=None):
|
||||
def meshCompute(mobj):
|
||||
"""Compute the mesh."""
|
||||
status = mobj.Compute()
|
||||
msg = ""
|
||||
|
||||
if status:
|
||||
logging.info("Mesh succesfully computed.")
|
||||
msg = "Computed"
|
||||
|
||||
else:
|
||||
logging.warning("Mesh is not computed.")
|
||||
msg = "Not computed"
|
||||
|
||||
logging.info("""meshCompute:
|
||||
status:\t{}""".format(msg))
|
||||
|
||||
def meshExport(mobj, path):
|
||||
"""
|
||||
@ -101,12 +110,15 @@ def meshExport(mobj, path):
|
||||
Parameters:
|
||||
path (string): full path to the expected directory.
|
||||
"""
|
||||
exportpath = os.path.join(path, "{}.unv".format(mobj.name))
|
||||
exportpath = path #os.path.join(path, "{}.unv".format(mobj.name))
|
||||
|
||||
try:
|
||||
mobj.ExportUNV(exportpath)
|
||||
|
||||
logging.info("""meshExport:
|
||||
format:\t{}""".format("unv"))
|
||||
|
||||
except:
|
||||
logging.error("Cannot export mesh to '{}'".format(exportpath))
|
||||
logging.error("""meshExport: Cannot export.""")
|
||||
|
||||
|
||||
|
@ -9,19 +9,35 @@ def startServer(port):
|
||||
|
||||
logging.info("Starting SALOME on port {} ...".format(port))
|
||||
|
||||
p = subprocess.run(["salome", "start", "--port", str(port), "-t"],
|
||||
p = subprocess.Popen(["salome", "start", "--port", str(port), "-t"],
|
||||
#shell = False,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE)
|
||||
|
||||
return p
|
||||
|
||||
def runExecute(port, scriptpath, *args):
|
||||
|
||||
logging.info("Starting SALOME on port {}".format(port))
|
||||
|
||||
p = subprocess.Popen(["salome", "start", "--shutdown-servers=1", "--port", str(port), "-t", scriptpath, "args:{}".format(", ".join([str(arg) for arg in args]))],
|
||||
stderr = subprocess.STDOUT)
|
||||
_, err = p.communicate()
|
||||
|
||||
if err:
|
||||
if p.returncode == 1:
|
||||
logging.error(err)
|
||||
|
||||
else:
|
||||
logging.warning(err)
|
||||
|
||||
return p.returncode
|
||||
|
||||
def killServer(port):
|
||||
|
||||
logging.info("Terminating SALOME on port {} ...".format(port))
|
||||
|
||||
p = subprocess.run(["salome", "kill", str(port)],
|
||||
p = subprocess.Popen(["salome", "kill", str(port)],
|
||||
#shell = True,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE)
|
||||
@ -33,7 +49,7 @@ def remote(port, cmd):
|
||||
logging.info("Executing command in the SALOME on port {} ...".format(port))
|
||||
|
||||
# cmd = "python -m"; = "python -c"
|
||||
p = subprocess.run(["salome", "remote", "-p", str(port), "--", str(cmd)],
|
||||
p = subprocess.Popen(["salome", "remote", "-p", str(port), "--", str(cmd)],
|
||||
#shell = True,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE)
|
||||
|
287
temp/run.dirty.py
Normal file
287
temp/run.dirty.py
Normal file
@ -0,0 +1,287 @@
|
||||
import os, sys
|
||||
from collections import namedtuple
|
||||
import time
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
import multiprocessing
|
||||
|
||||
ROOT = os.getcwd()
|
||||
sys.path.append(ROOT)
|
||||
|
||||
LOG = os.path.join(ROOT, "logs")
|
||||
BUILD = os.path.join(ROOT, "build")
|
||||
|
||||
from src import utils
|
||||
from src import salome_utils
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
if not os.path.exists(LOG):
|
||||
os.makedirs(LOG)
|
||||
|
||||
if not os.path.exists(BUILD):
|
||||
os.makedirs(BUILD)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/cubic.log".format(LOG))
|
||||
])
|
||||
|
||||
start_time = time.monotonic()
|
||||
logging.info("Started at {}".format(timedelta(seconds=start_time)))
|
||||
|
||||
|
||||
#nprocs = os.cpu_count()
|
||||
#port = 2810
|
||||
#salomeServers = []
|
||||
#salomeServer = namedtuple("salomeServer", ["process", "port"])
|
||||
|
||||
#for n in range(nprocs):
|
||||
# while not utils.portIsFree:
|
||||
# port += 1
|
||||
|
||||
# p = multiprocessing.Process(target = salome_utils.startServer, args = (port,))
|
||||
#s = salomeServer(salome_utils.startServer(port), port)
|
||||
# s = salomeServer(p, port)
|
||||
|
||||
# salomeServers.append(s)
|
||||
# port += 1
|
||||
|
||||
#var = []
|
||||
|
||||
# TODO: pass it to samples in namedtuples
|
||||
# get sample.directions and etc ..
|
||||
structures = [
|
||||
"simpleCubic",
|
||||
"bodyCenteredCubic",
|
||||
"faceCenteredCubic"
|
||||
]
|
||||
directions = [
|
||||
[1, 0, 0],
|
||||
[0, 0, 1],
|
||||
#[1, 1, 1]
|
||||
]
|
||||
|
||||
#cmd = """python -c
|
||||
#\"import sys;
|
||||
#sys.append('{}');
|
||||
#import samples;
|
||||
#samples.genMesh('{}', {}, {}, '{}');
|
||||
#\"
|
||||
#""".replace("\n", "")
|
||||
Task = namedtuple("Task", ["structure", "coeff", "direction", "saveto"])
|
||||
tasks = []
|
||||
|
||||
for structure in structures:
|
||||
if structure == "simpleCubic":
|
||||
theta = [c * 0.01 for c in range(1, 14)]
|
||||
|
||||
elif structure == "faceCenteredCubic":
|
||||
theta = []
|
||||
|
||||
elif structure == "bodyCenteredCubic":
|
||||
theta = []
|
||||
|
||||
for coeff in theta:
|
||||
for direction in directions:
|
||||
saveto = os.path.join(BUILD, structure, "coeff-{}".format(coeff),
|
||||
"direction-{}{}{}".format(direction[0], direction[1], direction[2]))
|
||||
|
||||
if not os.path.exists(saveto):
|
||||
os.makedirs(saveto)
|
||||
|
||||
direction_ = "".join([str(coord) for coord in direction])
|
||||
t = Task(structure, coeff, direction_, os.path.join(saveto, "mesh.unv"))
|
||||
tasks.append(t)
|
||||
#tasks.append(cmd.format(ROOT, structure, coeff, direction, BUILD))
|
||||
|
||||
logging.info("tasks: {}".format(len(tasks)))
|
||||
#n = 0
|
||||
#for cmd in tasks:
|
||||
# var.append((salomeServer[n].port, cmd))
|
||||
# n = n + 1 if n < 3 else 0
|
||||
|
||||
#for s in salomeServers:
|
||||
# s.process.start()
|
||||
|
||||
scriptpath = os.path.join(ROOT, "samples/__init__.py")
|
||||
port = 2810
|
||||
|
||||
for task in tasks:
|
||||
returncode = salome_utils.runExecute(port, scriptpath, task.structure, task.coeff, task.direction, task.saveto)
|
||||
|
||||
logging.info("Return code: {}".format(returncode))
|
||||
|
||||
if returncode == 1:
|
||||
break
|
||||
|
||||
#res = utils.parallel(nprocs, var, salome_utils.remote)
|
||||
#print(res)
|
||||
|
||||
#for s in salomeServers:
|
||||
# s.process.join()
|
||||
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
"""
|
||||
if __name__ == "__main__":
|
||||
###
|
||||
# SALOME
|
||||
#
|
||||
# Get main paths
|
||||
project = os.getcwd()
|
||||
src = os.path.join(project, "src")
|
||||
build = os.path.join(project, "build")
|
||||
|
||||
if not os.path.exists(build):
|
||||
os.makedirs(build)
|
||||
|
||||
# Logger
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/genmesh.log".format(build))
|
||||
])
|
||||
start_time = time.monotonic()
|
||||
|
||||
# Start in parallel
|
||||
processes = []
|
||||
structures = ["simpleCubic", "faceCenteredCubic", "bodyCenteredCubic"]
|
||||
directions = ["001"] #, "100", "111"]
|
||||
coefficients = [0.1] #[ alpha * 0.01 for alpha in range(1, 13 + 1) ]
|
||||
port = 2810
|
||||
|
||||
for structure in structures:
|
||||
for direction in directions:
|
||||
for coefficient in coefficients:
|
||||
src_path = os.path.join(src, "{}.py".format(structure))
|
||||
build_path = os.path.join(build,
|
||||
structure,
|
||||
"direction-{}".format(direction),
|
||||
"alpha-{}".format(coefficient))
|
||||
|
||||
if not os.path.exists(build_path):
|
||||
os.makedirs(build_path)
|
||||
|
||||
p = multiprocessing.Process(target = salome,
|
||||
args = (port, src_path, build_path, coefficient, direction))
|
||||
processes.append(p)
|
||||
p.start()
|
||||
logging.info("{} on port {}.".format(p, port))
|
||||
port += 1
|
||||
|
||||
for process in processes:
|
||||
process.join()
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
|
||||
|
||||
###
|
||||
# FOAM
|
||||
#
|
||||
# Get main paths
|
||||
project = os.getcwd()
|
||||
src = os.path.join(project, "src")
|
||||
build = os.path.join(project, "build")
|
||||
|
||||
if not os.path.exists(build):
|
||||
os.makedirs(build)
|
||||
|
||||
# Logger
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(levelname)s: %(message)s",
|
||||
handlers = [
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler("{}/foam.log".format(build))
|
||||
])
|
||||
start_time = time.monotonic()
|
||||
|
||||
# Main entry
|
||||
structures = ["simpleCubic"] #, "bc-cubic", "fc-cubic"]
|
||||
directions = ["001"] #, "100", "111"]
|
||||
coefficients = [0.1] #[ alpha * 0.01 for alpha in range(1, 13 + 1) ]
|
||||
|
||||
for structure in structures:
|
||||
for direction in directions:
|
||||
for coefficient in coefficients:
|
||||
foamCase = [ "0", "constant", "system" ]
|
||||
src_path = os.path.join(src, "{}Foam".format(structure))
|
||||
build_path = os.path.join(build,
|
||||
structure,
|
||||
"direction-{}".format(direction),
|
||||
"alpha-{}".format(coefficient))
|
||||
|
||||
|
||||
logging.info("Entry with parameters: {}, direction = {}, alpha = {}".format(structure, direction, coefficient))
|
||||
|
||||
logging.info("Copying baseFOAM case ...")
|
||||
for d in foamCase:
|
||||
if not os.path.exists(os.path.join(build_path, d)):
|
||||
shutil.copytree(os.path.join(src_path, d),
|
||||
os.path.join(build_path, d))
|
||||
|
||||
os.chdir(build_path)
|
||||
case_path = "."
|
||||
|
||||
logging.info("Importing mesh to foam ...")
|
||||
ideasUnvToFoam(case_path, "{}-{}-{}.unv".format(structure, direction, coefficient))
|
||||
|
||||
logging.info("Creating patches ...")
|
||||
createPatch(case_path)
|
||||
|
||||
logging.info("Scaling mesh ...")
|
||||
transformPoints(case_path, "(1e-5 1e-5 1e-5)")
|
||||
|
||||
logging.info("Checking mesh ...")
|
||||
checkMesh(case_path)
|
||||
|
||||
#logging.info("Changing mesh boundaries types ...")
|
||||
#foamDictionarySet(case_path, "constant/polyMesh/boundary", "entry0.wall.type", "wall")
|
||||
#foamDictionarySet(case_path, "constant/polyMesh/boundary", "entry0.symetryPlane.type", "symetryPlane")
|
||||
|
||||
logging.info("Decomposing case ...")
|
||||
decomposePar(case_path)
|
||||
|
||||
logging.info("Evaluating initial approximation via potentialFoam ...")
|
||||
potentialFoam(case_path)
|
||||
|
||||
logging.info("Preparing boundaryFields for simpleFoam ...")
|
||||
for n in range(4):
|
||||
foamDictionarySet(case_path, "processor{}/0/U".format(n),
|
||||
"boundaryField.inlet.type", "pressureInletVelocity")
|
||||
foamDictionarySet(case_path, "processor{}/0/U",
|
||||
"boundaryField.inlet.value", "uniform (0 0 0)")
|
||||
|
||||
logging.info("Calculating ...")
|
||||
simpleFoam(case_path)
|
||||
|
||||
os.chdir(project)
|
||||
|
||||
end_time = time.monotonic()
|
||||
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
|
||||
"""
|
Loading…
Reference in New Issue
Block a user