This commit is contained in:
Martin Diehl 2021-03-27 07:35:49 +01:00
parent 22195faecc
commit 111a1a76c6
5 changed files with 61 additions and 83 deletions

View File

@ -236,7 +236,7 @@ if remote:
sys.path.append(str(damask.solver.Marc().library_path))
import py_mentat
damask.util.report(scriptName, 'waiting to connect...')
print(scriptName+': waiting to connect...')
filenames = [os.path.join(tempfile._get_default_tempdir(), next(tempfile._get_candidate_names()) + '.mfd')]
try:
py_mentat.py_connect('',options.port)
@ -251,7 +251,7 @@ if remote:
for name in filenames:
while remote and not os.path.exists(name): time.sleep(0.5)
with open( name,'r') if name is not None else sys.stdin as fileIn:
damask.util.report(scriptName, name)
print(scriptName+': '+name)
mfd = parseMFD(fileIn)
add_servoLinks(mfd,[options.x,options.y,options.z])

View File

@ -194,7 +194,7 @@ if options.port is not None:
if filenames == []: filenames = [None]
for name in filenames:
damask.util.report(scriptName,name)
print(scriptName+': '+name)
geom = damask.Grid.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
material = geom.material.flatten(order='F')

View File

@ -270,10 +270,10 @@ class Test:
raise FileNotFoundError
def execute_inCurrentDir(self,cmd,streamIn=None,env=None):
def execute_inCurrentDir(self,cmd,env=None):
logging.info(cmd)
out,error = damask.util.execute(cmd,streamIn,self.dirCurrent())
out,error = damask.util.execute(cmd,self.dirCurrent())
logging.info(error)
logging.debug(out)

View File

@ -15,7 +15,6 @@ from . import version
# limit visibility
__all__=[
'srepr',
'report',
'emph','deemph','warn','strikeout',
'execute',
'show_progress',
@ -29,6 +28,21 @@ __all__=[
'DREAM3D_base_group', 'DREAM3D_cell_data_group'
]
# https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
# https://stackoverflow.com/questions/287871
_colors = {
'header' : '\033[95m',
'OK_blue': '\033[94m',
'OK_green': '\033[92m',
'warning': '\033[93m',
'fail': '\033[91m',
'end_color': '\033[0m',
'bold': '\033[1m',
'dim': '\033[2m',
'underline': '\033[4m',
'crossout': '\033[9m'
}
####################################################################################################
# Functions
####################################################################################################
@ -51,38 +65,24 @@ def srepr(arg,glue = '\n'):
return arg if isinstance(arg,str) else repr(arg)
def report(who = None,
what = None):
"""
Report script and file name.
DEPRECATED
"""
print( (emph(who)+': ' if who is not None else '') + (what if what is not None else '') + '\n' )
def emph(what):
"""Formats string with emphasis."""
return bcolors.BOLD+srepr(what)+bcolors.ENDC
return _colors['bold']+srepr(what)+_colors['end_color']
def deemph(what):
"""Formats string with deemphasis."""
return bcolors.DIM+srepr(what)+bcolors.ENDC
return _colors['dim']+srepr(what)+_colors['end_color']
def warn(what):
"""Formats string for warning."""
return bcolors.WARNING+emph(what)+bcolors.ENDC
return _colors['warning']+emph(what)+_colors['end_color']
def strikeout(what):
"""Formats string as strikeout."""
return bcolors.CROSSOUT+srepr(what)+bcolors.ENDC
return _colors['crossout']+srepr(what)+_colors['end_color']
def execute(cmd,
stream_in = None,
wd = './',
env = None):
def execute(cmd,wd='./',env=None):
"""
Execute command.
@ -90,33 +90,26 @@ def execute(cmd,
----------
cmd : str
Command to be executed.
stream_in : file object, optional
Input (via pipe) for executed process.
wd : str, optional
Working directory of process. Defaults to ./ .
env : dict, optional
Environment for execution.
"""
initialPath = os.getcwd()
myEnv = os.environ if env is None else env
os.chdir(wd)
print(f"executing '{cmd}' in '{wd}'")
process = subprocess.Popen(shlex.split(cmd),
process = subprocess.run(shlex.split(cmd),
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
stdin = subprocess.PIPE,
env = myEnv)
stdout, stderr = [i for i in (process.communicate() if stream_in is None
else process.communicate(stream_in.read().encode('utf-8')))]
os.chdir(initialPath)
stdout = stdout.decode('utf-8').replace('\x08','')
stderr = stderr.decode('utf-8').replace('\x08','')
env = os.environ if env is None else env,
cwd = wd,
encoding = 'utf-8')
if process.returncode != 0:
print(stdout)
print(stderr)
print(process.stdout)
print(process.stderr)
raise RuntimeError(f"'{cmd}' failed with returncode {process.returncode}")
return stdout, stderr
return process.stdout, process.stderr
def show_progress(iterable,N_iter=None,prefix='',bar_length=50):
@ -403,9 +396,30 @@ def DREAM3D_cell_data_group(fname):
return cell_data_group
####################################################################################################
# Classes
####################################################################################################
class return_message:
"""Object with formatted return message."""
def __init__(self,message):
"""
Sets return message.
Parameters
----------
message : str or list of str
message for output to screen
"""
self.message = message
def __repr__(self):
"""Return message suitable for interactive shells."""
return srepr(self.message)
class _ProgressBar:
"""
Report progress of an interation as a status bar.
@ -454,43 +468,3 @@ class _ProgressBar:
if iteration == self.total - 1:
sys.stderr.write('\n')
sys.stderr.flush()
class bcolors:
"""
ASCII colors.
https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
https://stackoverflow.com/questions/287871
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
DIM = '\033[2m'
UNDERLINE = '\033[4m'
CROSSOUT = '\033[9m'
class return_message:
"""Object with formatted return message."""
def __init__(self,message):
"""
Sets return message.
Parameters
----------
message : str or list of str
message for output to screen
"""
self.message = message
def __repr__(self):
"""Return message suitable for interactive shells."""
return srepr(self.message)

View File

@ -431,6 +431,10 @@ class TestGrid:
reference = VTK.load(ref_path/f'get_grain_boundaries_8g12x15x20_{"".join(direction)}_{periodic}.vtu')
assert current.__repr__() == reference.__repr__()
@pytest.mark.parametrize('directions',[(1,2,'y'),('a','b','x'),[1]])
def test_get_grain_boundaries_invalid(self,default,directions):
with pytest.raises(ValueError):
default.get_grain_boundaries(directions=directions)
def test_load_DREAM3D(self,ref_path):
grain = Grid.load_DREAM3D(ref_path/'2phase_irregularGrid.dream3d','FeatureIds')