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)) sys.path.append(str(damask.solver.Marc().library_path))
import py_mentat 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')] filenames = [os.path.join(tempfile._get_default_tempdir(), next(tempfile._get_candidate_names()) + '.mfd')]
try: try:
py_mentat.py_connect('',options.port) py_mentat.py_connect('',options.port)
@ -251,7 +251,7 @@ if remote:
for name in filenames: for name in filenames:
while remote and not os.path.exists(name): time.sleep(0.5) 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: 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) mfd = parseMFD(fileIn)
add_servoLinks(mfd,[options.x,options.y,options.z]) 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] if filenames == []: filenames = [None]
for name in filenames: 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) geom = damask.Grid.load(StringIO(''.join(sys.stdin.read())) if name is None else name)
material = geom.material.flatten(order='F') material = geom.material.flatten(order='F')

View File

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

View File

@ -15,7 +15,6 @@ from . import version
# limit visibility # limit visibility
__all__=[ __all__=[
'srepr', 'srepr',
'report',
'emph','deemph','warn','strikeout', 'emph','deemph','warn','strikeout',
'execute', 'execute',
'show_progress', 'show_progress',
@ -29,6 +28,21 @@ __all__=[
'DREAM3D_base_group', 'DREAM3D_cell_data_group' '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 # Functions
#################################################################################################### ####################################################################################################
@ -51,38 +65,24 @@ def srepr(arg,glue = '\n'):
return arg if isinstance(arg,str) else repr(arg) 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): def emph(what):
"""Formats string with emphasis.""" """Formats string with emphasis."""
return bcolors.BOLD+srepr(what)+bcolors.ENDC return _colors['bold']+srepr(what)+_colors['end_color']
def deemph(what): def deemph(what):
"""Formats string with deemphasis.""" """Formats string with deemphasis."""
return bcolors.DIM+srepr(what)+bcolors.ENDC return _colors['dim']+srepr(what)+_colors['end_color']
def warn(what): def warn(what):
"""Formats string for warning.""" """Formats string for warning."""
return bcolors.WARNING+emph(what)+bcolors.ENDC return _colors['warning']+emph(what)+_colors['end_color']
def strikeout(what): def strikeout(what):
"""Formats string as strikeout.""" """Formats string as strikeout."""
return bcolors.CROSSOUT+srepr(what)+bcolors.ENDC return _colors['crossout']+srepr(what)+_colors['end_color']
def execute(cmd, def execute(cmd,wd='./',env=None):
stream_in = None,
wd = './',
env = None):
""" """
Execute command. Execute command.
@ -90,33 +90,26 @@ def execute(cmd,
---------- ----------
cmd : str cmd : str
Command to be executed. Command to be executed.
stream_in : file object, optional
Input (via pipe) for executed process.
wd : str, optional wd : str, optional
Working directory of process. Defaults to ./ . Working directory of process. Defaults to ./ .
env : dict, optional env : dict, optional
Environment for execution. Environment for execution.
""" """
initialPath = os.getcwd()
myEnv = os.environ if env is None else env
os.chdir(wd)
print(f"executing '{cmd}' in '{wd}'") print(f"executing '{cmd}' in '{wd}'")
process = subprocess.Popen(shlex.split(cmd), process = subprocess.run(shlex.split(cmd),
stdout = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE, stderr = subprocess.PIPE,
stdin = subprocess.PIPE, env = os.environ if env is None else env,
env = myEnv) cwd = wd,
stdout, stderr = [i for i in (process.communicate() if stream_in is None encoding = 'utf-8')
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','')
if process.returncode != 0: if process.returncode != 0:
print(stdout) print(process.stdout)
print(stderr) print(process.stderr)
raise RuntimeError(f"'{cmd}' failed with returncode {process.returncode}") 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): 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 return cell_data_group
#################################################################################################### ####################################################################################################
# Classes # 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: class _ProgressBar:
""" """
Report progress of an interation as a status bar. Report progress of an interation as a status bar.
@ -454,43 +468,3 @@ class _ProgressBar:
if iteration == self.total - 1: if iteration == self.total - 1:
sys.stderr.write('\n') sys.stderr.write('\n')
sys.stderr.flush() 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') reference = VTK.load(ref_path/f'get_grain_boundaries_8g12x15x20_{"".join(direction)}_{periodic}.vtu')
assert current.__repr__() == reference.__repr__() 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): def test_load_DREAM3D(self,ref_path):
grain = Grid.load_DREAM3D(ref_path/'2phase_irregularGrid.dream3d','FeatureIds') grain = Grid.load_DREAM3D(ref_path/'2phase_irregularGrid.dream3d','FeatureIds')