Mod: openfoam conda requirement
This commit is contained in:
parent
a4e9a8f8dc
commit
6bfbb83b77
@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
from datetime import datetime
|
||||
import os
|
||||
|
@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
from .utils import version, uniform, datReader
|
||||
from .foamfile import FoamFile
|
||||
|
@ -1,51 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
import os, sys
|
||||
import subprocess
|
||||
|
||||
import logging
|
||||
logger = logging.getLogger()
|
||||
|
||||
def application(name: str, *args: str, case: str = None, stderr: bool = True, useMPI: bool = False) -> int:
|
||||
|
||||
cmd = []
|
||||
|
||||
if useMPI:
|
||||
nprocs = os.cpu_count()
|
||||
cmd.extend(["mpirun", "-np", str(nprocs), "--oversubscribe"])
|
||||
|
||||
cmd.append(name)
|
||||
|
||||
if case:
|
||||
cmd.extend(["-case", case])
|
||||
|
||||
if args:
|
||||
cmd.extend([*args])
|
||||
|
||||
logger.info("{}: {}".format(name, [*args]))
|
||||
logpath = os.path.join(case if case else "", "{}.log".format(name))
|
||||
|
||||
with subprocess.Popen(cmd,
|
||||
stdout = subprocess.PIPE,
|
||||
stderr = subprocess.PIPE) as p, \
|
||||
open(logpath, "wb") as logfile:
|
||||
|
||||
for line in p.stdout:
|
||||
#sys.stdout.buffer.write(line)
|
||||
logfile.write(line)
|
||||
|
||||
#for line in p.stderr:
|
||||
# logfile.write(line)
|
||||
|
||||
out, err = p.communicate()
|
||||
logfile.write(err)
|
||||
|
||||
#if err and stderr:
|
||||
# logger.error("""{}:
|
||||
# {}""".format(name, str(err, "utf-8")))
|
||||
|
||||
return out, err, p.returncode
|
||||
|
||||
|
116
anisotropy/openfoam/conversion.py
Normal file
116
anisotropy/openfoam/conversion.py
Normal file
@ -0,0 +1,116 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pathlib
|
||||
from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile
|
||||
from PyFoam.Basics.FoamFileGenerator import FoamFileGenerator
|
||||
import numpy as np
|
||||
|
||||
from . import utils
|
||||
|
||||
|
||||
def read_foamfile(filename: str) -> tuple[dict, dict]:
|
||||
"""Read a FoamFile.
|
||||
|
||||
:param filename:
|
||||
Path to the file.
|
||||
:return:
|
||||
Two dictionaries that contains header and content information
|
||||
of the FoamFile.
|
||||
"""
|
||||
path = pathlib.Path(filename).resolve()
|
||||
ppf = ParsedParameterFile(path)
|
||||
header = ppf.header or {}
|
||||
content = ppf.content or {}
|
||||
|
||||
return header, content
|
||||
|
||||
|
||||
def write_foamfile(header: dict, content: dict, filename: str):
|
||||
"""Write a FoamFile to the file.
|
||||
|
||||
:param header:
|
||||
Header block with the FoamFile metadata.
|
||||
:param content:
|
||||
Content block of the FoamFile.
|
||||
:param filename:
|
||||
Path to the file.
|
||||
"""
|
||||
path = pathlib.Path(filename).resolve()
|
||||
|
||||
# preformat
|
||||
header = (
|
||||
FoamFileGenerator({}, header = header)
|
||||
.makeString()[ :-2]
|
||||
.replace("\n ", "\n" + 4 * " ")
|
||||
)
|
||||
content = (
|
||||
FoamFileGenerator(content)
|
||||
.makeString()[ :-1]
|
||||
.replace("\n ", "\n" + 4 * " ")
|
||||
.replace(" \t// " + 73 * "*" + " //", "")
|
||||
.replace(" /* empty */ ", "")
|
||||
)
|
||||
|
||||
with open(path, "w") as outfile:
|
||||
outfile.write(utils.template(header, content) + "\n")
|
||||
|
||||
|
||||
def read_dat(filename: str):
|
||||
"""Read dat file.
|
||||
|
||||
:param filename:
|
||||
Path to the file.
|
||||
:return:
|
||||
Dictionary with arrays. Keys are created according file header
|
||||
block or numerated with string numbers if header is not found.
|
||||
"""
|
||||
path = pathlib.Path(filename).resolve()
|
||||
header = []
|
||||
content = []
|
||||
|
||||
with open(path, "r") as infile:
|
||||
for line in infile.readlines():
|
||||
if line.startswith("#"):
|
||||
header.append(line)
|
||||
|
||||
else:
|
||||
content.append(line)
|
||||
|
||||
columns = []
|
||||
|
||||
if header[-1].find(":") < 0:
|
||||
for column in header[-1].replace("#", "").split("\t"):
|
||||
columns.append(column.strip())
|
||||
|
||||
header.pop(-1)
|
||||
|
||||
else:
|
||||
for column in range(len(content[0].split("\t"))):
|
||||
columns.append(str(column))
|
||||
|
||||
output = {}
|
||||
|
||||
for row in header:
|
||||
key, value = row.replace("#", "").split(":")
|
||||
|
||||
try:
|
||||
value = float(value.strip())
|
||||
|
||||
except Exception:
|
||||
value = value.strip()
|
||||
|
||||
output[key.strip()] = value
|
||||
|
||||
for column in columns:
|
||||
output[column] = []
|
||||
|
||||
for row in content:
|
||||
values = row.split("\t")
|
||||
|
||||
for column, value in zip(columns, values):
|
||||
output[column].append(float(value))
|
||||
|
||||
for key in output.keys():
|
||||
output[key] = np.asarray(output[key])
|
||||
|
||||
return output
|
@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
from anisotropy.openfoam.foamfile import FoamFile
|
||||
import os, shutil
|
||||
|
@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
from anisotropy.openfoam.utils import version
|
||||
from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile
|
||||
|
@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
@ -1,6 +1,4 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
from typing import List
|
||||
from .runner import FoamRunner
|
||||
|
@ -1,89 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# This file is part of anisotropy.
|
||||
# License: GNU GPL version 3, see the file "LICENSE" for details.
|
||||
|
||||
from __future__ import annotations
|
||||
from numpy.typing import ndarray, ArrayLike
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from numpy import ndarray
|
||||
#from .application import application
|
||||
|
||||
def version() -> str:
|
||||
|
||||
def version() -> str | None:
|
||||
"""Version of the current OpenFOAM installation.
|
||||
|
||||
:return:
|
||||
Version string or None if installation is not found.
|
||||
"""
|
||||
return os.environ.get("WM_PROJECT_VERSION")
|
||||
|
||||
|
||||
def foamCleanCustom(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 ""
|
||||
def template(header: dict, content: dict) -> str:
|
||||
"""Render FoamFile with current template.
|
||||
|
||||
for d in rmDirs:
|
||||
if os.path.exists(os.path.join(path, d)):
|
||||
shutil.rmtree(os.path.join(path, d))
|
||||
:param header:
|
||||
Header block with the FoamFile metadata.
|
||||
:param content:
|
||||
Content block of the FoamFile.
|
||||
:return:
|
||||
Generated string of the whole FoamFile.
|
||||
"""
|
||||
limit = 78
|
||||
desc = [
|
||||
"/*--------------------------------*- C++ -*----------------------------------*\\",
|
||||
"| ========= | |",
|
||||
"| \\\\ / F ield | OpenFOAM: The Open Source CFD Toolbox |",
|
||||
"| \\\\ / O peration |",
|
||||
"| \\\\ / A nd | |",
|
||||
"| \\\\/ M anipulation | |",
|
||||
"\\*---------------------------------------------------------------------------*/"
|
||||
]
|
||||
desc[3] += " Version: {}".format(version() or "missed")
|
||||
desc[3] += " " * (limit - len(desc[3])) + "|"
|
||||
afterheader = "// " + 37 * "* " + "//"
|
||||
endfile = "// " + 73 * "*" + " //"
|
||||
|
||||
#def foamClean(case: str = None):
|
||||
# rmDirs = ["0", "constant", "system"]
|
||||
# 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))
|
||||
#
|
||||
# application("foamCleanTutorials", useMPI = False, case = case, stderr = True)
|
||||
return "\n".join([*desc, header, afterheader, content, endfile])
|
||||
|
||||
def uniform(value) -> str:
|
||||
if type(value) == list or type(value) == tuple or type(value) == ndarray:
|
||||
|
||||
def uniform(value: ArrayLike | float | int) -> str:
|
||||
"""Convert value to the OpenFOAM uniform representation.
|
||||
|
||||
:param value:
|
||||
Vector or scalar value.
|
||||
:return:
|
||||
Uniform string representation.
|
||||
"""
|
||||
if type(value) in [list, tuple, ndarray]:
|
||||
return f"uniform ({ value[0] } { value[1] } { value[2] })"
|
||||
|
||||
elif type(value) == int or type(value) == float:
|
||||
elif type(value) in [int, float]:
|
||||
return f"uniform { value }"
|
||||
|
||||
else:
|
||||
return ""
|
||||
|
||||
def datReader(filename: str):
|
||||
header = []
|
||||
content = []
|
||||
|
||||
with open(filename, "r") as io:
|
||||
for line in io.readlines():
|
||||
if line.startswith("#"):
|
||||
header.append(line)
|
||||
|
||||
else:
|
||||
content.append(line)
|
||||
|
||||
columns = []
|
||||
|
||||
if header[-1].find(":") < 0:
|
||||
for column in header[-1].replace("#", "").split("\t"):
|
||||
columns.append(column.strip())
|
||||
|
||||
header.pop(-1)
|
||||
|
||||
else:
|
||||
for column in range(len(content[0].split("\t"))):
|
||||
columns.append(str(column))
|
||||
|
||||
output = {}
|
||||
|
||||
for row in header:
|
||||
key, value = row.replace("#", "").split(":")
|
||||
|
||||
try:
|
||||
value = float(value.strip())
|
||||
|
||||
except:
|
||||
value = value.strip()
|
||||
|
||||
output[key.strip()] = value
|
||||
|
||||
for column in columns:
|
||||
output[column] = []
|
||||
|
||||
for row in content:
|
||||
values = row.split("\t")
|
||||
|
||||
for column, value in zip(columns, values):
|
||||
output[column].append(float(value))
|
||||
|
||||
return output
|
@ -1,7 +1,6 @@
|
||||
name: anisotropy
|
||||
channels:
|
||||
- l-nafaryus
|
||||
- local
|
||||
- conda-forge
|
||||
dependencies:
|
||||
- python>=3.9
|
||||
@ -9,3 +8,4 @@ dependencies:
|
||||
- sqlite
|
||||
- occt
|
||||
- l-nafaryus::netgen
|
||||
- l-nafaryus::openfoam
|
||||
|
Loading…
Reference in New Issue
Block a user