Mod: openfoam conda requirement

This commit is contained in:
L-Nafaryus 2022-01-28 12:41:09 +05:00
parent a4e9a8f8dc
commit 6bfbb83b77
No known key found for this signature in database
GPG Key ID: C76D8DCD2727DBB7
10 changed files with 162 additions and 137 deletions

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# This file is part of anisotropy.
# License: GNU GPL version 3, see the file "LICENSE" for details.
from datetime import datetime from datetime import datetime
import os import os

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- 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 .utils import version, uniform, datReader
from .foamfile import FoamFile from .foamfile import FoamFile

View File

@ -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

View 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

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- 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 from anisotropy.openfoam.foamfile import FoamFile
import os, shutil import os, shutil

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- 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 anisotropy.openfoam.utils import version
from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# This file is part of anisotropy.
# License: GNU GPL version 3, see the file "LICENSE" for details.
import os import os
import subprocess import subprocess

View File

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- 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 typing import List
from .runner import FoamRunner from .runner import FoamRunner

View File

@ -1,89 +1,61 @@
# -*- coding: utf-8 -*- # -*- 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 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") return os.environ.get("WM_PROJECT_VERSION")
def foamCleanCustom(case: str = None): def template(header: dict, content: dict) -> str:
rmDirs = ["0", "constant", "system", "postProcessing", "logs"] """Render FoamFile with current template.
rmDirs.extend([ "processor{}".format(n) for n in range(os.cpu_count()) ])
path = case if case else ""
for d in rmDirs: :param header:
if os.path.exists(os.path.join(path, d)): Header block with the FoamFile metadata.
shutil.rmtree(os.path.join(path, d)) :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): return "\n".join([*desc, header, afterheader, content, endfile])
# 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)
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] })" 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 }" return f"uniform { value }"
else: else:
return "" 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

View File

@ -1,7 +1,6 @@
name: anisotropy name: anisotropy
channels: channels:
- l-nafaryus - l-nafaryus
- local
- conda-forge - conda-forge
dependencies: dependencies:
- python>=3.9 - python>=3.9
@ -9,3 +8,4 @@ dependencies:
- sqlite - sqlite
- occt - occt
- l-nafaryus::netgen - l-nafaryus::netgen
- l-nafaryus::openfoam