New: poetry

Mod: shaping test
This commit is contained in:
L-Nafaryus 2021-11-18 00:48:17 +05:00
parent 6d90fa1c33
commit 8920e89928
No known key found for this signature in database
GPG Key ID: C76D8DCD2727DBB7
13 changed files with 1647 additions and 238 deletions

3
.gitignore vendored
View File

@ -20,3 +20,6 @@ env/
*.out
*.egg-info
.ipynb_checkpoints/
.coverage
.venv
.pytest_cache

View File

@ -7,6 +7,71 @@ import ast
import os, sys, shutil
import logging
class LiteralOption(click.Option):
def type_cast_value(self, ctx, value):
try:
return ast.literal_eval(value)
except:
raise click.BadParameter(f"{ value } (Type error)")
class KeyValueOption(click.Option):
def _convert(self, ctx, value):
if not value:
return {}
if value.find("=") == -1:
raise click.BadParameter(f"{ value } (Missed '=')")
params = value.split("=")
if not len(params) == 2:
raise click.BadParameter(f"{ value } (Syntax error)")
key, val = params[0].strip(), params[1].strip()
if val[0].isalpha():
val = f"'{ val }'"
try:
return { key: ast.literal_eval(val) }
except:
raise click.BadParameter(f"{ value } (Type error)")
def type_cast_value(self, ctx, value):
if isinstance(value, list):
return [ self._convert(ctx, val) for val in value ]
else:
return self._convert(ctx, value)
class CliListOption(click.Option):
def _convert(self, ctx, value):
if not value:
return []
output = [ val for val in value.split(",") ]
if "" in output:
raise click.BadParameter(f"{ value } (Trying to pass empty item)")
return output
def type_cast_value(self, ctx, value):
if isinstance(value, list):
return [ self._convert(ctx, val) for val in value ]
else:
return self._convert(ctx, value)
@click.group()
def anisotropy():
pass
@anisotropy.command()
@click.option(
"-P", "--path", "path",
@ -71,67 +136,8 @@ def compute(path, configFile, nprocs, stage, overwrite):
baseRunner.parallel(queue)
##############
class LiteralOption(click.Option):
def type_cast_value(self, ctx, value):
try:
return ast.literal_eval(value)
except:
raise click.BadParameter(f"{ value } (Type error)")
class KeyValueOption(click.Option):
def _convert(self, ctx, value):
if not value:
return {}
if value.find("=") == -1:
raise click.BadParameter(f"{ value } (Missed '=')")
params = value.split("=")
if not len(params) == 2:
raise click.BadParameter(f"{ value } (Syntax error)")
key, val = params[0].strip(), params[1].strip()
if val[0].isalpha():
val = f"'{ val }'"
try:
return { key: ast.literal_eval(val) }
except:
raise click.BadParameter(f"{ value } (Type error)")
def type_cast_value(self, ctx, value):
if isinstance(value, list):
return [ self._convert(ctx, val) for val in value ]
else:
return self._convert(ctx, value)
class CliListOption(click.Option):
def _convert(self, ctx, value):
if not value:
return []
output = [ val for val in value.split(",") ]
if "" in output:
raise click.BadParameter(f"{ value } (Trying to pass empty item)")
return output
def type_cast_value(self, ctx, value):
if isinstance(value, list):
return [ self._convert(ctx, val) for val in value ]
else:
return self._convert(ctx, value)
def version():
msg = "Missed package anisotropy"
@ -237,7 +243,7 @@ def update(force, params, path):
paramsAll = [ entry for entry in paramsAll if args["theta"] == entry["structure"]["theta"] ]
from anisotropy.core.models import Structure, Mesh
from numpy
#from numpy
for entry in paramsAll:
database.update(entry)

View File

@ -11,25 +11,74 @@ class Mesh(object):
self.geometry = OCCGeometry(shape)
self.mesh = None
# Parameters
self.maxh = 0.2
self.curvaturesafety = 5
self.segmentsperedge = 3
self.grading = 0.1
self.chartdistfac = 5
self.linelengthfac = 3
self.closeedgefac = 5
self.minedgelen = 2.0
self.surfmeshcurvfac = 5.0
self.optsteps2d = 5
self.optsteps3d = 5
@property
def parameters(self):
return meshing.MeshingParameters(
maxh = 0.2,
curvaturesafety = 5,
segmentsperedge = 3,
grading = 0.1,
chartdistfac = 5,
linelengthfac = 3,
closeedgefac = 5,
minedgelen = 2.0,
surfmeshcurvfac = 5.0,
optsteps2d = 5,
optsteps3d = 5
maxh = self.maxh,
curvaturesafety = self.curvaturesafety,
segmentsperedge = self.segmentsperedge,
grading = self.grading,
chartdistfac = self.chartdistfac,
linelengthfac = self.linelengthfac,
closeedgefac = self.closeedgefac,
minedgelen = self.minedgelen,
surfmeshcurvfac = self.surfmeshcurvfac,
optsteps2d = self.optsteps2d,
optsteps3d = self.optsteps3d
)
def build(self):
self.mesh = self.geometry.GenerateMesh(self.parameters)
def export(self, filename: str):
"""Export a shape.
Supported formats: vol, mesh.
:param filename:
Name of the file to store the given shape in.
:return:
Output, error messages and returncode
"""
out, err, returncode = "", "", 0
ext = os.path.splitext(filename)[1][1: ]
try:
# TODO: write correct boundary names
if ext == "vol":
self.mesh.Save(filename)
elif ext == "mesh":
self.mesh.Export(filename, "Neutral Format")
else:
raise NotImplementedError(f"{ ext } is not supported")
except NotImplementedError as e:
err = e
returncode = 1
except Exception as e:
err = e
returncode = 1
return out, err, returncode
def doubleExport(self):
pass

View File

@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
# This file is part of anisotropy.
# License: GNU GPL version 3, see the file "LICENSE" for details.
import anisotropy.openfoam as openfoam
from openfoam.presets import (
ControlDict, FvSchemes, FvSolution,
TransportProperties, TurbulenceProperties, CreatePatchDict,
P, U
)
from openfoam.foamcase import FoamCase
class OnePhaseFlow(FoamCase):
def __init__(self):
FoamCase.__init__(self)
controlDict = ControlDict()
controlDict.update(
startFrom = "latestTime",
endTime = 5000,
writeInterval = 100,
runTimeModifiable = "true"
)
fvSchemes = FvSchemes()
fvSolution = FvSolution()
fvSolution["solvers"]["U"].update(
nSweeps = 2,
tolerance = 1e-08
)
fvSolution["solvers"]["Phi"] = dict(
solver = "GAMG",
smoother = "DIC",
cacheAgglomeration = "yes",
agglomerator = "faceAreaPair",
nCellsInCoarsestLevel = 10,
mergeLevels = 1,
tolerance = 1e-06,
relTol = 0.01
)
fvSolution["potentialFlow"] = dict(
nNonOrthogonalCorrectors = 20,
PhiRefCell = 0,
PhiRefPoint = 0,
PhiRefValue = 0,
Phi = 0
)
fvSolution["cache"] = { "grad(U)": None }
fvSolution["SIMPLE"].update(
nNonOrthogonalCorrectors = 10,
residualControl = dict(
p = 1e-05,
U = 1e-05
)
)
fvSolution["relaxationFactors"]["equations"]["U"] = 0.5
transportProperties = TransportProperties()
transportProperties.update(
nu = 1e-06
)
turbulenceProperties = TurbulenceProperties()
turbulenceProperties.content = dict(
simulationType = "laminar"
)
createPatchDict = CreatePatchDict()
createPatchDict["patches"] = []
for patch in ["inlet", "outlet", "wall", "strips", *[ f"symetry{ n }" for n in range(6) ]]:
newPatch = dict(
name = patch,
patchInfo = dict(
type = "patch",
inGroups = [patch]
),
constructFrom = "patches",
patches = [ f"smesh_{ patch }" ]
)
match patch:
case "wall" | "strips":
newPatch["patchInfo"].update(
type = "wall",
inGroups = [ "wall" ]
)
case patch if patch.find("symetry") == 0:
newPatch["patchInfo"]["inGroups"] = [ "symetryPlane" ]
createPatchDict["patches"].append(newPatch)
boundaries = [ "inlet", "outlet", "symetryPlane", "wall", "strips" ]
p = P()
p["boundaryField"] = {}
u = U()
u["boundaryField"] = {}
# ISSUE: add proxy from geometry direction to outlet boundaryField.
for boundary in boundaries:
match boundary:
case "inlet":
p["boundaryField"][boundary] = dict(
type = "fixedValue",
value = "uniform 1e-3"
)
u["boundaryField"][boundary] = dict(
type = "fixedValue",
value = "uniform (0 0 -6e-5)" # * direction
)
case "outlet":
p["boundaryField"][boundary] = dict(
type = "fixedValue",
value = "uniform 0"
)
u["boundaryField"][boundary] = dict(
type = "zeroGradient",
)
case _:
p["boundaryField"][boundary] = dict(
type = "zeroGradient"
)
u["boundaryField"][boundary] = dict(
type = "fixedValue",
value = "uniform (0 0 0)"
)
self.extend([
controlDict, fvSchemes, fvSolution, createPatchDict,
transportProperties, turbulenceProperties,
p, u
])
def build(self):
# TODO: configure working directory (FoamCase)
self.write()
openfoam.ideasUnvToFoam("mesh.unv")
openfoam.createPatch()
openfoam.checkMesh()
openfoam.transformPoints((1e-5, 1e-5, 1e-5))
openfoam.renumberMesh()
openfoam.potentialFoam()
self.read()
self.solution.U["boundaryField"]["outlet"] = dict(
type = "pressureInletVelocity",
value = "uniform (0 0 0)" # * direction
)
self.write()
openfoam.simpleFoam()

1298
poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

55
pyproject.toml Normal file
View File

@ -0,0 +1,55 @@
[tool.poetry]
name = "anisotropy"
version = "1.2.0"
description = "Anisotropy of permeability in the periodic porous media."
authors = ["George Kusayko <gkusayko@gmail.com>"]
license = "GPL-3.0-only"
readme = "README.rst"
repository = "https://github.com/L-Nafaryus/anisotropy"
keywords = ["anisotropy", "console", "CFD"]
classifiers = [
"Environment :: Console",
"Operating System :: POSIX",
"Operating System :: Unix",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Programming Language :: Python :: 3.9"
]
packages = [
{ include = "anisotropy" }
]
[tool.poetry.scripts]
anisotropy = "anisotropy.core.cli:anisotropy"
[tool.poetry.dependencies]
python = ">=3.9,<3.11"
toml = "^0.10.2"
peewee = "^3.14.8"
numpy = "^1.21.4"
pandas = "^1.3.4"
matplotlib = "^3.5.0"
pyfoam = "^2021.6"
click = "^8.0.3"
pyqt5 = "^5.15.6"
[tool.poetry.dev-dependencies]
pytest = "^5.2"
vulture = "^2.3"
pytest-cov = "^3.0.0"
pycodestyle = "^2.8.0"
pydeps = {version = "^1.10.12", optional = true}
peewee-erd = {version = "^0.1.3", optional = true}
Sphinx = {version = "^4.3.0", optional = true}
sphinx-rtd-theme = {version = "^1.0.0", optional = true}
[tool.poetry.extras]
analyze = ["jupyterlab", "seaborn", "sklearn"]
docs = ["Sphinx", "sphinx-rtd-theme", "pydeps", "peewee-erd"]
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

View File

@ -1 +0,0 @@
@arbennett/base16-gruvbox-dark

View File

@ -1,10 +0,0 @@
wheel
numpy
pyquaternion
toml
peewee
pandas
Click
matplotlib
pyqt5
PyFoam

View File

@ -1,89 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of anisotropy.
# License: GNU GPL version 3, see the file "LICENSE" for details.
import os
from setuptools import setup
import anisotropy
def read(filename, split = False):
content = ""
with open(os.path.join(os.path.dirname(__file__), filename), "r") as io:
content = io.read()
return content.strip().split("\n") if split else content
def findall(directory):
return [
os.path.join(directory, f) for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))
]
def main():
setup(
name = "anisotropy",
description = "Anisotropy",
long_description = read("README.rst"),
long_description_content_type = "text/x-rst",
version = anisotropy.__version__,
author = anisotropy.__author__,
author_email = anisotropy.__email__,
license = anisotropy.__license__,
url = "https://github.com/L-Nafaryus/anisotropy",
project_urls = {
"Source": "https://github.com/L-Nafaryus/anisotropy"
},
keywords = "anisotropy console CFD",
classifiers = [
"Environment :: Console",
"Operating System :: POSIX",
"Operating System :: Unix",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Programming Language :: Python :: 3.9"
],
data_files = [
("share/doc/anisotropy", findall("docs")),
("share/doc/anisotropy/source", findall("docs/source")),
("share/doc/anisotropy/source/static", findall("docs/source/static")),
("share/doc/anisotropy/source/notes", findall("docs/source/notes"))
],
package_data = {
"anisotropy": [
"config/default.toml",
"config/bashrc"
]
},
packages = (
"anisotropy",
"anisotropy.config",
"anisotropy.core",
"anisotropy.openfoam",
"anisotropy.salomepl",
"anisotropy.samples"
),
python_requires = ">=3.6",
install_requires = read("requirements.txt", True),
extras_require = {
"documentation": ["Sphinx", "sphinx-rtd-theme", "pydeps", "peewee-erd" ],
"extra": ["jupyterlab", "seaborn", "sklearn"]
},
entry_points = {
"console_scripts": [
"anisotropy=anisotropy.core.cli:anisotropy"
]
}
)
if __name__ == "__main__":
main()

View File

@ -1,44 +0,0 @@
import os
import unittest
unittest.TestLoader.sortTestMethodsUsing = None
# TODO: update tests
class TestAnisotropy(unittest.TestCase):
def setUp(self):
from anisotropy.core.main import Anisotropy
self.model = Anisotropy()
def test_01_create_db(self):
self.model.db.setup()
path = os.path.join(self.model.env["db_path"], "anisotropy.db")
self.assertTrue(os.path.exists(path))
def test_02_load_from_scratch(self):
passed = True
try:
paramsAll = self.model.loadFromScratch()
for entry in paramsAll:
self.model.update(entry)
except Exception as e:
passed = False
print(e)
self.assertTrue(passed)
def test_03_load_db(self):
self.model.load("simple", [1.0, 0.0, 0.0], 0.01)
self.assertEqual(self.model.params["structure"]["type"], "simple")
def tearDown(self):
#os.removedirs(self.model.env["BUILD"])
#os.removedirs(self.model.env["LOG"])
pass
if __name__ == "__main__":
unittest.main()

View File

@ -1,22 +0,0 @@
import os
import unittest
unittest.TestLoader.sortTestMethodsUsing = None
class TestFaceCentered(unittest.TestCase):
def setUp(self):
self.outputPath = os.path.join(os.path.abspath("."), "tests/test_shaping_output")
os.makedirs(self.outputPath, exist_ok = True)
def test_faceCentered_lattice(self):
from anisotropy.shaping import FaceCentered
fc = FaceCentered([1, 0, 0], alpha = 0.01, filletsEnabled = True)
fc.build()
fc.lattice.WriteStep(os.path.join(self.outputPath, "fc_lattice.step"))
def tearDown(self):
pass
if __name__ == "__main__":
unittest.main()

View File

@ -38,6 +38,11 @@ class TestShaping(unittest.TestCase):
bodyCentered001.export(os.path.join(self.outputPath, "bodyCentered001.step"))
bodyCentered111.export(os.path.join(self.outputPath, "bodyCentered111.step"))
def test_faceCentered_lattice(self):
fc = self.shaping.FaceCentered([1, 0, 0], alpha = 0.01, filletsEnabled = True)
fc.build()
fc.lattice.WriteStep(os.path.join(self.outputPath, "fc_lattice.step"))
def test_faceCentered(self):
faceCentered100 = self.shaping.FaceCentered(direction = [1, 0, 0], alpha = 0.01)
faceCentered001 = self.shaping.FaceCentered(direction = [0, 0, 1], alpha = 0.01)

1
thirdparty/netgen vendored Submodule

@ -0,0 +1 @@
Subproject commit 9477fb032184d16ff12c50b2e1ee8c868fa1f23a