Performing parallezation

This commit is contained in:
L-Nafaryus 2021-03-24 21:27:12 +05:00
parent 34b993715a
commit 89dd850ab8
No known key found for this signature in database
GPG Key ID: C76D8DCD2727DBB7
9 changed files with 185 additions and 39 deletions

82
run.py Normal file → Executable file
View File

@ -1,13 +1,36 @@
import os, sys import os, sys
from collections import namedtuple from collections import namedtuple
import time
import logging
from datetime import timedelta
import multiprocessing
ROOT = os.getcwd() ROOT = os.getcwd()
sys.path.append(ROOT) sys.path.append(ROOT)
import src.utils LOG = os.path.join(ROOT, "logs")
import src.salome_utils BUILD = os.path.join(ROOT, "build")
from src import utils
from src import salome_utils
if __name__ == "__main__": 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() nprocs = os.cpu_count()
port = 2810 port = 2810
@ -18,11 +41,14 @@ if __name__ == "__main__":
while not utils.portIsFree: while not utils.portIsFree:
port += 1 port += 1
s = salomeServer(salome_utils.startServer(port), port) p = multiprocessing.Process(target = salome_utils.startServer, args = (port,))
#s = salomeServer(salome_utils.startServer(port), port)
s = salomeServer(p, port)
salomeServers.append(s) salomeServers.append(s)
port += 1
var = [] var = []
cmd = "python "
# TODO: pass it to samples in namedtuples # TODO: pass it to samples in namedtuples
# get sample.directions and etc .. # get sample.directions and etc ..
@ -34,15 +60,50 @@ if __name__ == "__main__":
directions = [ directions = [
[1, 0, 0], [1, 0, 0],
[0, 0, 1], [0, 0, 1],
[1, 1, 1] #[1, 1, 1]
] ]
cmd += "-m " cmd = """python -c
\"import sys;
sys.append('{}');
import samples;
samples.genMesh('{}', {}, {}, '{}');
\"
""".replace("\n", "")
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:
tasks.append(cmd.format(ROOT, structure, coeff, direction, BUILD))
logging.info("tasks: {}".format(tasks))
n = 0
for cmd in tasks:
var.append((salomeServer[n].port, cmd)) var.append((salomeServer[n].port, cmd))
n = n + 1 if n < 3 else 0
utils.parallel(nprocs, var, salome_utils.execute) for s in salomeServers:
s.process.start()
#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)))
@ -60,6 +121,7 @@ if __name__ == "__main__":
"""
if __name__ == "__main__": if __name__ == "__main__":
### ###
# SALOME # SALOME
@ -199,4 +261,4 @@ if __name__ == "__main__":
end_time = time.monotonic() end_time = time.monotonic()
logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time))) logging.info("Elapsed time: {}".format(timedelta(seconds=end_time - start_time)))
"""

View File

@ -1,3 +1,57 @@
from .simpleCubic import simpleCubic from .simpleCubic import simpleCubic
from .faceCenteredCubic import faceCenteredCubic from .faceCenteredCubic import faceCenteredCubic
from .bodyCenteredCubic import bodyCenteredCubic 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()
structure = _G.get(stype)
if structure:
salome.salome_init()
grains, cubic, rhombohedron = structure(theta)
fd = namedtuple("fd", ["x", "y", "z"])
geometry = cubic
if flowdirection == [1, 1, 1]:
geometry = rhombohedron
direction = fd([1, 1, 1], [1, -1, 1], [1, -1, -1])
else:
geometry = cubic
if flowdirection == [1, 0, 0]:
direction = fd([1, 1, 0], [1, -1, 0], [0, 0, 1])
if flowdirection == [0, 0, 1]:
direction = fd([0, 0, 1], [1, -1, 0], [1, 1, 0])
boundary = geometry_utils.boundaryCreate(geometry, direction, grains)
fineness = 3
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]))
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"))
salome.salome_close()
else:
raise Exception("Unknown sample function")

View File

@ -118,6 +118,7 @@ def bodyCenteredCubic(alpha):
if salome.sg.hasDesktop(): if salome.sg.hasDesktop():
salome.sg.updateObjBrowser() salome.sg.updateObjBrowser()
# Preparation
grains = geompy.ExtractShapes(Up_Down, geompy.ShapeType["SOLID"], True) grains = geompy.ExtractShapes(Up_Down, geompy.ShapeType["SOLID"], True)
grains += geompy.ExtractShapes(Middle, geompy.ShapeType["SOLID"], True) grains += geompy.ExtractShapes(Middle, geompy.ShapeType["SOLID"], True)

View File

@ -126,6 +126,7 @@ def faceCenteredCubic(alpha):
if salome.sg.hasDesktop(): if salome.sg.hasDesktop():
salome.sg.updateObjBrowser() salome.sg.updateObjBrowser()
# Preparation
grains = geompy.ExtractShapes(Up_Down, geompy.ShapeType["SOLID"], True) grains = geompy.ExtractShapes(Up_Down, geompy.ShapeType["SOLID"], True)
grains += geompy.ExtractShapes(Middle, geompy.ShapeType["SOLID"], True) grains += geompy.ExtractShapes(Middle, geompy.ShapeType["SOLID"], True)

View File

@ -100,4 +100,11 @@ def simpleCubic(alpha):
if salome.sg.hasDesktop(): if salome.sg.hasDesktop():
salome.sg.updateObjBrowser() salome.sg.updateObjBrowser()
# Preparation
#Cut_1 = geompy.MakeRotation(Cut_1, OZ, -pi_4)
grains = geompy.ExtractShapes(Multi_Translation_3, geompy.ShapeType["SOLID"], True)
grains = geompy.MakeFuseList(grains, False, False)
return Multi_Translation_3, Cut_1, Cut_2 return Multi_Translation_3, Cut_1, Cut_2

View File

@ -12,13 +12,12 @@ def getGeom():
return geompy return geompy
def rotate(gobj, ang): def rotate(gobj, ang):
x = geompy.MakeVectorDXDYDZ(1, 0, 0), x = geompy.MakeVectorDXDYDZ(1, 0, 0)
y = geompy.MakeVectorDXDYDZ(0, 1, 0), y = geompy.MakeVectorDXDYDZ(0, 1, 0)
z = geompy.MakeVectorDXDYDZ(0, 0, 1) z = geompy.MakeVectorDXDYDZ(0, 0, 1)
# yaw # yaw
rotated = geompy.MakeRotation(gobj, z, ang[2]) rotated = geompy.MakeRotation(gobj, z, ang[2])
print(rotated)
# pitch # pitch
rotated = geompy.MakeRotation(rotated, y, ang[1]) rotated = geompy.MakeRotation(rotated, y, ang[1])
# roll # roll
@ -30,9 +29,9 @@ def createGroup(gobj, planelist, grains, name):
gr = geompy.CreateGroup(gobj, geompy.ShapeType["FACE"], name) gr = geompy.CreateGroup(gobj, geompy.ShapeType["FACE"], name)
grcomp = geompy.MakeCompound(planelist) grcomp = geompy.MakeCompound(planelist)
grcut = geompy.MakeCutList(grcomp, [grains], True) #grcut = geompy.MakeCutList(grcomp, [grains], False)
gip = geompy.GetInPlace(gobj, grcut, True) gip = geompy.GetInPlace(gobj, grcomp, True)
faces = geompy.SubShapeAll(gip, geompy.ShapeType["FACE"]) faces = geompy.SubShapeAll(gip, geompy.ShapeType["FACE"])
geompy.UnionList(gr, faces) geompy.UnionList(gr, faces)
@ -42,18 +41,33 @@ def boundaryCreate(gobj, dvec, grains):
xvec = geompy.MakeVector( xvec = geompy.MakeVector(
geompy.MakeVertex(0, 0, 0), geompy.MakeVertex(0, 0, 0),
geompy.MakeVertex(dvec[0], dvec[1], dvec[2])) geompy.MakeVertex(dvec.x[0], dvec.x[1], dvec.x[2]))
#xvec = rotate(dvec, self.angle) #xvec = rotate(xvec, [0, 0, 0.25 * math.pi])
yvec = rotate(xvec, [0.5 * math.pi, 0, 0]) #yvec = rotate(xvec, [0.5 * math.pi, 0, 0])
zvec = rotate(xvec, [0, 0.5 * math.pi, 0]) #zvec = rotate(xvec, [0, 0.5 * math.pi, 0])
yvec = geompy.MakeVector(
geompy.MakeVertex(0, 0, 0),
geompy.MakeVertex(dvec.y[0], dvec.y[1], dvec.y[2]))
zvec = geompy.MakeVector(
geompy.MakeVertex(0, 0, 0),
geompy.MakeVertex(dvec.z[0], dvec.z[1], dvec.z[2]))
geompy.addToStudy(xvec, "xvec")
geompy.addToStudy(yvec, "yvec")
geompy.addToStudy(zvec, "zvec")
logging.info("boundaryCreate: dvec = {}".format(dvec)) logging.info("boundaryCreate: dvec = {}".format(dvec))
planes = geompy.ExtractShapes(gobj, geompy.ShapeType["FACE"], True) planes = geompy.ExtractShapes(gobj, geompy.ShapeType["FACE"], False)
planes = geompy.MakeCompound(planes)
planes = geompy.MakeCutList(planes, [grains], False)
planes = geompy.ExtractShapes(planes, geompy.ShapeType["FACE"], False)
inletplanes = [] inletplanes = []
outletplanes = [] outletplanes = []
uplanes = [] #uplanes = []
fwplanes = [] fwplanes = []
bwplanes = [] bwplanes = []
@ -62,9 +76,10 @@ def boundaryCreate(gobj, dvec, grains):
for plane in planes: for plane in planes:
nvec = geompy.GetNormal(plane) nvec = geompy.GetNormal(plane)
xang = geompy.GetAngle(nvec, xvec) xang = round(geompy.GetAngle(nvec, xvec), 0)
yang = geompy.GetAngle(nvec, yvec) yang = round(geompy.GetAngle(nvec, yvec), 0)
zang = geompy.GetAngle(nvec, zvec) zang = round(geompy.GetAngle(nvec, zvec), 0)
print(xang, yang, zang, sep="\t")
if xang == 0: if xang == 0:
inletplanes.append(plane) inletplanes.append(plane)
@ -85,16 +100,16 @@ def boundaryCreate(gobj, dvec, grains):
rplanes.append(plane) rplanes.append(plane)
logging.info( logging.info(
"boundaryCreate: inletplanes = {}, outletplanes = {}, hplanes = {}".format( "boundaryCreate: planes = {}, inletplanes = {}, outletplanes = {}".format(
len(inletplane), len(outletplane), len(hplanes))) len(planes), len(inletplanes), len(outletplanes)))
logging.info( logging.info(
"boundaryCreate: fwplanes = {}, bwplanes = {}, lplanes = {}, rplanes = {}".format( "boundaryCreate: fwplanes = {}, bwplanes = {}, lplanes = {}, rplanes = {}".format(
len(fwplanes), len(bwplanes), len(lplanes), len(rplanes))) len(fwplanes), len(bwplanes), len(lplanes), len(rplanes)))
# Main groups # Main groups
inlet = createGroup(gobj, inletplane, grains, "inlet") inlet = createGroup(gobj, inletplanes, grains, "inlet")
outlet = createGroup(gobj, grains, outletplane, "outlet") outlet = createGroup(gobj, outletplanes, grains, "outlet")
symetryPlaneFW = createGroup(gobj, fwplanes, grains, "symetryPlaneFW") symetryPlaneFW = createGroup(gobj, fwplanes, grains, "symetryPlaneFW")
symetryPlaneBW = createGroup(gobj, bwplanes, grains, "symetryPlaneBW") symetryPlaneBW = createGroup(gobj, bwplanes, grains, "symetryPlaneBW")

View File

@ -1,4 +1,4 @@
import salome #import salome
import subprocess import subprocess
import logging import logging
@ -9,31 +9,32 @@ def startServer(port):
logging.info("Starting SALOME on port {} ...".format(port)) logging.info("Starting SALOME on port {} ...".format(port))
p = subprocess.Popen(["salome", "start", "--port", str(port), "-t"], p = subprocess.run(["salome", "start", "--port", str(port), "-t"],
shell = False, #shell = False,
stdout = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE) stderr = subprocess.PIPE)
return p return p
def killServer(port): def killServer(port):
logging.info("Terminating SALOME on port {} ...".format(port)) logging.info("Terminating SALOME on port {} ...".format(port))
p = subprocess.Popen(["salome", "kill", str(port)], p = subprocess.run(["salome", "kill", str(port)],
shell = True, #shell = True,
stdout = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE) stderr = subprocess.PIPE)
return p return p
def execute(port, cmd): def remote(port, cmd):
logging.info("Executing command in the SALOME on port {} ...".format(port)) logging.info("Executing command in the SALOME on port {} ...".format(port))
# cmd = "python -m"; = "python -c" # cmd = "python -m"; = "python -c"
p = subprocess.Popen(["salome", "remote", "-p", str(port), "--", str(cmd)], p = subprocess.run(["salome", "remote", "-p", str(port), "--", str(cmd)],
shell = True, #shell = True,
stdout = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE) stderr = subprocess.PIPE)

View File

@ -1,5 +1,6 @@
from multiprocessing import Queue, Process, cpu_count from multiprocessing import Queue, Process, cpu_count
import socket import socket
import logging
def queue(cmd, qin, qout, *args): def queue(cmd, qin, qout, *args):
@ -12,7 +13,7 @@ def queue(cmd, qin, qout, *args):
break break
# Execute command # Execute command
res = cmd(var, *args) res = cmd(*var, *args)
# Put results to the queue # Put results to the queue
qout.put((pos, res)) qout.put((pos, res))
@ -30,6 +31,10 @@ def parallel(np, var, cmd):
qin = Queue(1) qin = Queue(1)
qout = Queue() qout = Queue()
logging.info("cpu count: {}".format(np))
logging.info("var: {}".format(var))
logging.info("cmd: {}".format(cmd))
# Create processes # Create processes
for n in range(nprocs): for n in range(nprocs):
pargs = [cmd, qin, qout] pargs = [cmd, qin, qout]