2019-05-30 23:32:55 +05:30
|
|
|
import sys
|
2020-03-09 18:09:20 +05:30
|
|
|
import datetime
|
2019-05-30 23:32:55 +05:30
|
|
|
import os
|
|
|
|
import subprocess
|
|
|
|
import shlex
|
2020-11-10 01:50:56 +05:30
|
|
|
import re
|
2020-03-09 18:09:20 +05:30
|
|
|
import fractions
|
2020-02-21 11:51:45 +05:30
|
|
|
from functools import reduce
|
2015-10-09 11:21:58 +05:30
|
|
|
from optparse import Option
|
2019-05-20 23:24:57 +05:30
|
|
|
|
2020-02-21 11:51:45 +05:30
|
|
|
import numpy as np
|
2021-03-20 04:19:41 +05:30
|
|
|
import h5py
|
2019-05-20 23:24:57 +05:30
|
|
|
|
2020-08-24 13:25:41 +05:30
|
|
|
from . import version
|
2020-08-24 02:53:23 +05:30
|
|
|
|
2020-04-10 16:02:33 +05:30
|
|
|
# limit visibility
|
|
|
|
__all__=[
|
|
|
|
'srepr',
|
|
|
|
'croak',
|
|
|
|
'report',
|
2020-11-15 15:23:23 +05:30
|
|
|
'emph','deemph','warn','strikeout',
|
2020-04-10 16:02:33 +05:30
|
|
|
'execute',
|
|
|
|
'show_progress',
|
|
|
|
'scale_to_coprime',
|
2020-11-10 01:50:56 +05:30
|
|
|
'project_stereographic',
|
2020-09-28 11:10:43 +05:30
|
|
|
'hybrid_IA',
|
2020-04-10 16:02:33 +05:30
|
|
|
'return_message',
|
|
|
|
'extendableOption',
|
2020-11-10 01:50:56 +05:30
|
|
|
'execution_stamp',
|
2020-11-15 00:21:15 +05:30
|
|
|
'shapeshifter', 'shapeblender',
|
2021-03-20 04:19:41 +05:30
|
|
|
'extend_docstring', 'extended_docstring',
|
2021-03-23 18:58:56 +05:30
|
|
|
'DREAM3D_base_group', 'DREAM3D_cell_data_group'
|
2020-04-10 16:02:33 +05:30
|
|
|
]
|
|
|
|
|
|
|
|
####################################################################################################
|
|
|
|
# Functions
|
|
|
|
####################################################################################################
|
2016-03-04 19:52:01 +05:30
|
|
|
def srepr(arg,glue = '\n'):
|
2020-02-22 04:36:51 +05:30
|
|
|
r"""
|
2020-06-24 23:43:09 +05:30
|
|
|
Join arguments with glue string.
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
arg : iterable
|
2020-03-15 02:23:48 +05:30
|
|
|
Items to join.
|
2020-02-22 03:55:22 +05:30
|
|
|
glue : str, optional
|
2020-11-15 17:36:26 +05:30
|
|
|
Glue used for joining operation. Defaults to \n.
|
2020-02-22 03:55:22 +05:30
|
|
|
|
|
|
|
"""
|
|
|
|
if (not hasattr(arg, "strip") and
|
|
|
|
(hasattr(arg, "__getitem__") or
|
|
|
|
hasattr(arg, "__iter__"))):
|
|
|
|
return glue.join(str(x) for x in arg)
|
|
|
|
return arg if isinstance(arg,str) else repr(arg)
|
|
|
|
|
|
|
|
|
2016-03-04 19:52:01 +05:30
|
|
|
def croak(what, newline = True):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""
|
|
|
|
Write formated to stderr.
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-11-14 23:54:31 +05:30
|
|
|
DEPRECATED
|
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
what : str or iterable
|
2020-03-15 02:23:48 +05:30
|
|
|
Content to be displayed.
|
2020-02-22 03:55:22 +05:30
|
|
|
newline : bool, optional
|
2020-03-15 02:23:48 +05:30
|
|
|
Separate items of what by newline. Defaults to True.
|
2020-02-22 03:55:22 +05:30
|
|
|
|
|
|
|
"""
|
2020-03-21 04:12:23 +05:30
|
|
|
if what is not None:
|
2020-02-22 03:55:22 +05:30
|
|
|
sys.stderr.write(srepr(what,glue = '\n') + ('\n' if newline else ''))
|
|
|
|
sys.stderr.flush()
|
|
|
|
|
|
|
|
|
2016-07-18 19:50:39 +05:30
|
|
|
def report(who = None,
|
|
|
|
what = None):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""
|
2020-11-15 15:23:23 +05:30
|
|
|
Report script and file name.
|
2020-02-22 01:34:23 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
DEPRECATED
|
2020-02-22 01:34:23 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
"""
|
|
|
|
croak( (emph(who)+': ' if who is not None else '') + (what if what is not None else '') + '\n' )
|
2015-09-23 02:30:18 +05:30
|
|
|
|
2016-04-24 21:50:55 +05:30
|
|
|
|
2015-08-22 22:32:49 +05:30
|
|
|
def emph(what):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""Formats string with emphasis."""
|
|
|
|
return bcolors.BOLD+srepr(what)+bcolors.ENDC
|
|
|
|
|
2016-08-25 21:29:04 +05:30
|
|
|
def deemph(what):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""Formats string with deemphasis."""
|
|
|
|
return bcolors.DIM+srepr(what)+bcolors.ENDC
|
|
|
|
|
2020-11-15 15:23:23 +05:30
|
|
|
def warn(what):
|
|
|
|
"""Formats string for warning."""
|
|
|
|
return bcolors.WARNING+emph(what)+bcolors.ENDC
|
2016-08-25 21:29:04 +05:30
|
|
|
|
2019-05-28 06:44:09 +05:30
|
|
|
def strikeout(what):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""Formats string as strikeout."""
|
|
|
|
return bcolors.CROSSOUT+srepr(what)+bcolors.ENDC
|
2019-05-28 06:44:09 +05:30
|
|
|
|
|
|
|
|
2016-03-21 18:21:56 +05:30
|
|
|
def execute(cmd,
|
2020-06-21 02:21:00 +05:30
|
|
|
stream_in = None,
|
2019-06-07 21:21:27 +05:30
|
|
|
wd = './',
|
|
|
|
env = None):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""
|
|
|
|
Execute command.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
cmd : str
|
2020-03-15 02:23:48 +05:30
|
|
|
Command to be executed.
|
2020-06-21 02:21:00 +05:30
|
|
|
stream_in : file object, optional
|
2020-03-15 02:23:48 +05:30
|
|
|
Input (via pipe) for executed process.
|
2020-02-22 03:55:22 +05:30
|
|
|
wd : str, optional
|
2020-03-15 02:23:48 +05:30
|
|
|
Working directory of process. Defaults to ./ .
|
|
|
|
env : dict, optional
|
|
|
|
Environment for execution.
|
2020-02-22 03:55:22 +05:30
|
|
|
|
|
|
|
"""
|
|
|
|
initialPath = os.getcwd()
|
|
|
|
myEnv = os.environ if env is None else env
|
2020-04-26 18:22:27 +05:30
|
|
|
os.chdir(wd)
|
2020-09-19 12:03:15 +05:30
|
|
|
print(f"executing '{cmd}' in '{wd}'")
|
2020-02-22 03:55:22 +05:30
|
|
|
process = subprocess.Popen(shlex.split(cmd),
|
|
|
|
stdout = subprocess.PIPE,
|
|
|
|
stderr = subprocess.PIPE,
|
|
|
|
stdin = subprocess.PIPE,
|
|
|
|
env = myEnv)
|
2020-06-21 02:21:00 +05:30
|
|
|
stdout, stderr = [i for i in (process.communicate() if stream_in is None
|
|
|
|
else process.communicate(stream_in.read().encode('utf-8')))]
|
2020-04-26 18:22:27 +05:30
|
|
|
os.chdir(initialPath)
|
2020-06-21 02:21:00 +05:30
|
|
|
stdout = stdout.decode('utf-8').replace('\x08','')
|
|
|
|
stderr = stderr.decode('utf-8').replace('\x08','')
|
2020-02-22 03:55:22 +05:30
|
|
|
if process.returncode != 0:
|
2021-02-26 11:05:42 +05:30
|
|
|
print(stdout)
|
|
|
|
print(stderr)
|
2020-09-19 12:03:15 +05:30
|
|
|
raise RuntimeError(f"'{cmd}' failed with returncode {process.returncode}")
|
2020-06-21 02:21:00 +05:30
|
|
|
return stdout, stderr
|
2020-02-22 03:55:22 +05:30
|
|
|
|
|
|
|
|
2020-04-10 16:02:33 +05:30
|
|
|
def show_progress(iterable,N_iter=None,prefix='',bar_length=50):
|
|
|
|
"""
|
|
|
|
Decorate a loop with a status bar.
|
|
|
|
|
|
|
|
Use similar like enumerate.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
iterable : iterable/function with yield statement
|
|
|
|
Iterable (or function with yield statement) to be decorated.
|
|
|
|
N_iter : int
|
|
|
|
Total # of iterations. Needed if number of iterations can not be obtained as len(iterable).
|
|
|
|
prefix : str, optional.
|
|
|
|
Prefix string.
|
|
|
|
bar_length : int, optional
|
|
|
|
Character length of bar. Defaults to 50.
|
|
|
|
|
|
|
|
"""
|
|
|
|
status = _ProgressBar(N_iter if N_iter else len(iterable),prefix,bar_length)
|
|
|
|
|
|
|
|
for i,item in enumerate(iterable):
|
|
|
|
yield item
|
|
|
|
status.update(i)
|
|
|
|
|
|
|
|
|
|
|
|
def scale_to_coprime(v):
|
2020-11-15 17:36:26 +05:30
|
|
|
"""
|
|
|
|
Scale vector to co-prime (relatively prime) integers.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
v : numpy.ndarray of shape (:)
|
|
|
|
Vector to scale.
|
|
|
|
|
|
|
|
"""
|
2020-06-25 11:59:36 +05:30
|
|
|
MAX_DENOMINATOR = 1000000
|
2020-04-10 16:02:33 +05:30
|
|
|
|
|
|
|
def get_square_denominator(x):
|
|
|
|
"""Denominator of the square of a number."""
|
|
|
|
return fractions.Fraction(x ** 2).limit_denominator(MAX_DENOMINATOR).denominator
|
|
|
|
|
|
|
|
def lcm(a, b):
|
|
|
|
"""Least common multiple."""
|
2020-11-01 23:50:52 +05:30
|
|
|
# Python 3.9 provides math.lcm, see https://stackoverflow.com/questions/51716916.
|
2020-04-10 16:02:33 +05:30
|
|
|
return a * b // np.gcd(a, b)
|
|
|
|
|
2021-02-22 13:05:15 +05:30
|
|
|
m = (np.array(v) * reduce(lcm, map(lambda x: int(get_square_denominator(x)),v)) ** 0.5).astype(int)
|
2020-06-25 04:07:33 +05:30
|
|
|
m = m//reduce(np.gcd,m)
|
|
|
|
|
2020-09-24 00:40:10 +05:30
|
|
|
with np.errstate(invalid='ignore'):
|
2020-09-19 23:08:32 +05:30
|
|
|
if not np.allclose(np.ma.masked_invalid(v/m),v[np.argmax(abs(v))]/m[np.argmax(abs(v))]):
|
2020-09-18 20:00:22 +05:30
|
|
|
raise ValueError(f'Invalid result {m} for input {v}. Insufficient precision?')
|
2020-06-25 04:07:33 +05:30
|
|
|
|
|
|
|
return m
|
2020-04-10 16:02:33 +05:30
|
|
|
|
|
|
|
|
2021-02-28 05:02:53 +05:30
|
|
|
def project_stereographic(vector,direction='z',normalize=True,keepdims=False):
|
2020-11-10 01:50:56 +05:30
|
|
|
"""
|
|
|
|
Apply stereographic projection to vector.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
vector : numpy.ndarray of shape (...,3)
|
|
|
|
Vector coordinates to be projected.
|
2021-02-28 05:16:20 +05:30
|
|
|
direction : str
|
|
|
|
Projection direction 'x', 'y', or 'z'.
|
2021-02-27 21:45:01 +05:30
|
|
|
Defaults to 'z'.
|
2021-02-28 05:02:53 +05:30
|
|
|
normalize : bool
|
|
|
|
Ensure unit length of input vector. Defaults to True.
|
|
|
|
keepdims : bool
|
|
|
|
Maintain three-dimensional output coordinates.
|
|
|
|
Default two-dimensional output uses right-handed frame spanned by
|
|
|
|
the next and next-next axis relative to the projection direction,
|
|
|
|
e.g. x-y when projecting along z and z-x when projecting along y.
|
2020-11-10 01:50:56 +05:30
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
2021-02-28 05:02:53 +05:30
|
|
|
coordinates : numpy.ndarray of shape (...,2 | 3)
|
2020-11-10 01:50:56 +05:30
|
|
|
Projected coordinates.
|
|
|
|
|
2021-02-28 05:02:53 +05:30
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
>>> project_stereographic(np.ones(3))
|
|
|
|
[0.3660254, 0.3660254]
|
|
|
|
>>> project_stereographic(np.ones(3),direction='x',normalize=False,keepdims=True)
|
|
|
|
[0, 0.5, 0.5]
|
|
|
|
>>> project_stereographic([0,1,1],direction='y',normalize=True,keepdims=False)
|
|
|
|
[0.41421356, 0]
|
|
|
|
|
2020-11-10 01:50:56 +05:30
|
|
|
"""
|
2021-02-28 05:16:20 +05:30
|
|
|
shift = 'zyx'.index(direction)
|
2021-02-27 21:45:01 +05:30
|
|
|
v_ = np.roll(vector/np.linalg.norm(vector,axis=-1,keepdims=True) if normalize else vector,
|
|
|
|
shift,axis=-1)
|
|
|
|
return np.roll(np.block([v_[...,:2]/(1+np.abs(v_[...,2:3])),np.zeros_like(v_[...,2:3])]),
|
2021-02-28 05:02:53 +05:30
|
|
|
-shift if keepdims else 0,axis=-1)[...,:3 if keepdims else 2]
|
2020-11-10 01:50:56 +05:30
|
|
|
|
|
|
|
|
2020-08-25 00:20:40 +05:30
|
|
|
def execution_stamp(class_name,function_name=None):
|
|
|
|
"""Timestamp the execution of a (function within a) class."""
|
2020-08-24 02:53:23 +05:30
|
|
|
now = datetime.datetime.now().astimezone().strftime('%Y-%m-%d %H:%M:%S%z')
|
2020-08-25 00:20:40 +05:30
|
|
|
_function_name = '' if function_name is None else f'.{function_name}'
|
2020-08-24 13:25:41 +05:30
|
|
|
return f'damask.{class_name}{_function_name} v{version} ({now})'
|
2020-08-24 02:53:23 +05:30
|
|
|
|
|
|
|
|
2020-11-15 17:36:26 +05:30
|
|
|
def hybrid_IA(dist,N,rng_seed=None):
|
|
|
|
"""
|
|
|
|
Hybrid integer approximation.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
dist : numpy.ndarray
|
|
|
|
Distribution to be approximated
|
|
|
|
N : int
|
|
|
|
Number of samples to draw.
|
|
|
|
rng_seed : {None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional
|
|
|
|
A seed to initialize the BitGenerator. Defaults to None.
|
|
|
|
If None, then fresh, unpredictable entropy will be pulled from the OS.
|
|
|
|
|
|
|
|
"""
|
2020-09-29 20:45:10 +05:30
|
|
|
N_opt_samples,N_inv_samples = (max(np.count_nonzero(dist),N),0) # random subsampling if too little samples requested
|
2020-09-28 11:10:43 +05:30
|
|
|
|
|
|
|
scale_,scale,inc_factor = (0.0,float(N_opt_samples),1.0)
|
|
|
|
while (not np.isclose(scale, scale_)) and (N_inv_samples != N_opt_samples):
|
2020-09-29 20:45:10 +05:30
|
|
|
repeats = np.rint(scale*dist).astype(int)
|
|
|
|
N_inv_samples = np.sum(repeats)
|
2020-09-28 11:10:43 +05:30
|
|
|
scale_,scale,inc_factor = (scale,scale+inc_factor*0.5*(scale - scale_), inc_factor*2.0) \
|
|
|
|
if N_inv_samples < N_opt_samples else \
|
|
|
|
(scale_,0.5*(scale_ + scale), 1.0)
|
|
|
|
|
2020-11-15 17:36:26 +05:30
|
|
|
return np.repeat(np.arange(len(dist)),repeats)[np.random.default_rng(rng_seed).permutation(N_inv_samples)[:N]]
|
2020-09-28 11:10:43 +05:30
|
|
|
|
|
|
|
|
2020-11-10 01:50:56 +05:30
|
|
|
def shapeshifter(fro,to,mode='left',keep_ones=False):
|
|
|
|
"""
|
|
|
|
Return a tuple that reshapes 'fro' to become broadcastable to 'to'.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
fro : tuple
|
|
|
|
Original shape of array.
|
|
|
|
to : tuple
|
|
|
|
Target shape of array after broadcasting.
|
|
|
|
len(to) cannot be less than len(fro).
|
|
|
|
mode : str, optional
|
|
|
|
Indicates whether new axes are preferably added to
|
|
|
|
either 'left' or 'right' of the original shape.
|
|
|
|
Defaults to 'left'.
|
|
|
|
keep_ones : bool, optional
|
|
|
|
Treat '1' in fro as literal value instead of dimensional placeholder.
|
|
|
|
Defaults to False.
|
|
|
|
|
|
|
|
"""
|
|
|
|
beg = dict(left ='(^.*\\b)',
|
|
|
|
right='(^.*?\\b)')
|
|
|
|
sep = dict(left ='(.*\\b)',
|
|
|
|
right='(.*?\\b)')
|
|
|
|
end = dict(left ='(.*?$)',
|
|
|
|
right='(.*$)')
|
|
|
|
fro = (1,) if not len(fro) else fro
|
|
|
|
to = (1,) if not len(to) else to
|
|
|
|
try:
|
|
|
|
grp = re.match(beg[mode]
|
|
|
|
+f',{sep[mode]}'.join(map(lambda x: f'{x}'
|
|
|
|
if x>1 or (keep_ones and len(fro)>1) else
|
|
|
|
'\\d+',fro))
|
|
|
|
+f',{end[mode]}',
|
|
|
|
','.join(map(str,to))+',').groups()
|
|
|
|
except AttributeError:
|
|
|
|
raise ValueError(f'Shapes can not be shifted {fro} --> {to}')
|
|
|
|
fill = ()
|
|
|
|
for g,d in zip(grp,fro+(None,)):
|
|
|
|
fill += (1,)*g.count(',')+(d,)
|
|
|
|
return fill[:-1]
|
|
|
|
|
|
|
|
|
|
|
|
def shapeblender(a,b):
|
|
|
|
"""
|
|
|
|
Return a shape that overlaps the rightmost entries of 'a' with the leftmost of 'b'.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
a : tuple
|
|
|
|
Shape of first array.
|
|
|
|
b : tuple
|
|
|
|
Shape of second array.
|
|
|
|
|
|
|
|
Examples
|
|
|
|
--------
|
|
|
|
>>> shapeblender((4,4,3),(3,2,1))
|
|
|
|
(4,4,3,2,1)
|
|
|
|
>>> shapeblender((1,2),(1,2,3))
|
|
|
|
(1,2,3)
|
|
|
|
>>> shapeblender((1,),(2,2,1))
|
|
|
|
(1,2,2,1)
|
|
|
|
>>> shapeblender((3,2),(3,2))
|
|
|
|
(3,2)
|
|
|
|
|
|
|
|
"""
|
|
|
|
i = min(len(a),len(b))
|
|
|
|
while i > 0 and a[-i:] != b[:i]: i -= 1
|
|
|
|
return a + b[i:]
|
|
|
|
|
|
|
|
|
2020-11-15 15:23:23 +05:30
|
|
|
def extend_docstring(extra_docstring):
|
|
|
|
"""
|
|
|
|
Decorator: Append to function's docstring.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
extra_docstring : str
|
|
|
|
Docstring to append.
|
|
|
|
|
|
|
|
"""
|
|
|
|
def _decorator(func):
|
|
|
|
func.__doc__ += extra_docstring
|
|
|
|
return func
|
|
|
|
return _decorator
|
|
|
|
|
|
|
|
|
|
|
|
def extended_docstring(f,extra_docstring):
|
|
|
|
"""
|
|
|
|
Decorator: Combine another function's docstring with a given docstring.
|
2020-11-15 00:21:15 +05:30
|
|
|
|
2020-11-15 15:23:23 +05:30
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
f : function
|
|
|
|
Function of which the docstring is taken.
|
|
|
|
extra_docstring : str
|
|
|
|
Docstring to append.
|
2020-11-15 00:21:15 +05:30
|
|
|
|
2020-11-15 15:23:23 +05:30
|
|
|
"""
|
|
|
|
def _decorator(func):
|
|
|
|
func.__doc__ = f.__doc__ + extra_docstring
|
|
|
|
return func
|
|
|
|
return _decorator
|
2020-11-15 00:21:15 +05:30
|
|
|
|
|
|
|
|
2021-03-20 04:19:41 +05:30
|
|
|
def DREAM3D_base_group(fname):
|
2021-03-23 18:58:56 +05:30
|
|
|
"""
|
|
|
|
Determine the base group of a DREAM.3D file.
|
|
|
|
|
|
|
|
The base group is defined as the group (folder) that contains
|
|
|
|
a 'SPACING' dataset in a '_SIMPL_GEOMETRY' group.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
fname : str
|
|
|
|
Filename of the DREAM.3D (HDF5) file.
|
|
|
|
|
|
|
|
"""
|
2021-03-20 04:19:41 +05:30
|
|
|
with h5py.File(fname,'r') as f:
|
|
|
|
base_group = f.visit(lambda path: path.rsplit('/',2)[0] if '_SIMPL_GEOMETRY/SPACING' in path else None)
|
2021-03-23 18:58:56 +05:30
|
|
|
|
2021-03-20 04:19:41 +05:30
|
|
|
if base_group is None:
|
2021-03-23 19:30:59 +05:30
|
|
|
raise ValueError(f'Could not determine base group in file {fname}.')
|
2021-03-23 18:58:56 +05:30
|
|
|
|
2021-03-20 04:19:41 +05:30
|
|
|
return base_group
|
|
|
|
|
2021-03-23 18:58:56 +05:30
|
|
|
def DREAM3D_cell_data_group(fname):
|
|
|
|
"""
|
|
|
|
Determine the cell data group of a DREAM.3D file.
|
|
|
|
|
|
|
|
The cell data group is defined as the group (folder) that contains
|
|
|
|
a dataset in the base group whose length matches the total number
|
|
|
|
of points as specified in '_SIMPL_GEOMETRY/DIMENSIONS'.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
fname : str
|
|
|
|
Filename of the DREAM.3D (HDF5) file.
|
|
|
|
|
|
|
|
"""
|
|
|
|
base_group = DREAM3D_base_group(fname)
|
|
|
|
with h5py.File(fname,'r') as f:
|
2021-03-23 19:30:59 +05:30
|
|
|
cells = tuple(f[os.path.join(base_group,'_SIMPL_GEOMETRY','DIMENSIONS')][()][::-1])
|
2021-03-23 18:58:56 +05:30
|
|
|
cell_data_group = f[base_group].visititems(lambda path,obj: path.split('/')[0] \
|
2021-03-23 19:30:59 +05:30
|
|
|
if isinstance(obj,h5py._hl.dataset.Dataset) and np.shape(obj)[:-1] == cells \
|
2021-03-23 18:58:56 +05:30
|
|
|
else None)
|
|
|
|
|
|
|
|
if cell_data_group is None:
|
2021-03-23 19:30:59 +05:30
|
|
|
raise ValueError(f'Could not determine cell data group in file {fname}/{base_group}.')
|
2021-03-23 18:58:56 +05:30
|
|
|
|
|
|
|
return cell_data_group
|
|
|
|
|
2020-04-10 16:02:33 +05:30
|
|
|
####################################################################################################
|
|
|
|
# Classes
|
|
|
|
####################################################################################################
|
2014-06-17 12:40:10 +05:30
|
|
|
class extendableOption(Option):
|
2020-02-22 03:55:22 +05:30
|
|
|
"""
|
|
|
|
Used for definition of new option parser action 'extend', which enables to take multiple option arguments.
|
2014-06-17 12:40:10 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
Adopted from online tutorial http://docs.python.org/library/optparse.html
|
|
|
|
DEPRECATED
|
|
|
|
"""
|
2019-01-05 15:11:49 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
ACTIONS = Option.ACTIONS + ("extend",)
|
|
|
|
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
|
|
|
|
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
|
|
|
|
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
|
2019-01-05 15:11:49 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
def take_action(self, action, dest, opt, value, values, parser):
|
2020-03-15 02:23:48 +05:30
|
|
|
if action == "extend":
|
|
|
|
lvalue = value.split(",")
|
|
|
|
values.ensure_value(dest, []).extend(lvalue)
|
|
|
|
else:
|
|
|
|
Option.take_action(self, action, dest, opt, value, values, parser)
|
2018-12-09 13:38:33 +05:30
|
|
|
|
2019-05-28 12:32:29 +05:30
|
|
|
|
2020-03-09 18:09:20 +05:30
|
|
|
class _ProgressBar:
|
|
|
|
"""
|
|
|
|
Report progress of an interation as a status bar.
|
|
|
|
|
|
|
|
Works for 0-based loops, ETA is estimated by linear extrapolation.
|
2019-09-20 01:02:15 +05:30
|
|
|
"""
|
2020-03-09 18:09:20 +05:30
|
|
|
|
|
|
|
def __init__(self,total,prefix,bar_length):
|
|
|
|
"""
|
|
|
|
Inititalize a progress bar to current time as basis for ETA estimation.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
total : int
|
2020-03-15 02:23:48 +05:30
|
|
|
Total # of iterations.
|
2020-03-09 18:09:20 +05:30
|
|
|
prefix : str
|
2020-03-15 02:23:48 +05:30
|
|
|
Prefix string.
|
2020-03-09 18:09:20 +05:30
|
|
|
bar_length : int
|
2020-03-15 02:23:48 +05:30
|
|
|
Character length of bar.
|
2020-03-09 18:09:20 +05:30
|
|
|
|
|
|
|
"""
|
|
|
|
self.total = total
|
|
|
|
self.prefix = prefix
|
|
|
|
self.bar_length = bar_length
|
|
|
|
self.start_time = datetime.datetime.now()
|
|
|
|
self.last_fraction = 0.0
|
|
|
|
|
2020-06-24 20:32:15 +05:30
|
|
|
sys.stderr.write(f"{self.prefix} {'░'*self.bar_length} 0% ETA n/a")
|
2020-03-09 18:09:20 +05:30
|
|
|
sys.stderr.flush()
|
|
|
|
|
|
|
|
def update(self,iteration):
|
|
|
|
|
|
|
|
fraction = (iteration+1) / self.total
|
2020-06-24 20:32:15 +05:30
|
|
|
filled_length = int(self.bar_length * fraction)
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-06-24 20:32:15 +05:30
|
|
|
if filled_length > int(self.bar_length * self.last_fraction):
|
|
|
|
bar = '█' * filled_length + '░' * (self.bar_length - filled_length)
|
2020-03-09 18:09:20 +05:30
|
|
|
delta_time = datetime.datetime.now() - self.start_time
|
|
|
|
remaining_time = (self.total - (iteration+1)) * delta_time / (iteration+1)
|
2021-02-26 11:05:42 +05:30
|
|
|
remaining_time -= datetime.timedelta(microseconds=remaining_time.microseconds) # remove μs
|
2020-06-25 01:04:51 +05:30
|
|
|
sys.stderr.write(f'\r{self.prefix} {bar} {fraction:>4.0%} ETA {remaining_time}')
|
2020-03-09 18:09:20 +05:30
|
|
|
sys.stderr.flush()
|
|
|
|
|
|
|
|
self.last_fraction = fraction
|
|
|
|
|
|
|
|
if iteration == self.total - 1:
|
|
|
|
sys.stderr.write('\n')
|
|
|
|
sys.stderr.flush()
|
|
|
|
|
2020-02-22 04:36:51 +05:30
|
|
|
|
2020-04-10 16:02:33 +05:30
|
|
|
class bcolors:
|
2019-09-20 01:02:15 +05:30
|
|
|
"""
|
2020-06-24 20:32:15 +05:30
|
|
|
ASCII colors.
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-04-10 16:02:33 +05:30
|
|
|
https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
|
|
|
|
https://stackoverflow.com/questions/287871
|
|
|
|
"""
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-04-10 16:02:33 +05:30
|
|
|
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'
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-03-06 02:24:47 +05:30
|
|
|
|
2020-03-19 13:15:25 +05:30
|
|
|
class return_message:
|
2020-02-22 03:55:22 +05:30
|
|
|
"""Object with formatted return message."""
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
def __init__(self,message):
|
|
|
|
"""
|
|
|
|
Sets return message.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
message : str or list of str
|
2020-03-15 02:23:48 +05:30
|
|
|
message for output to screen
|
2020-02-22 03:55:22 +05:30
|
|
|
|
|
|
|
"""
|
|
|
|
self.message = message
|
2020-03-09 18:09:20 +05:30
|
|
|
|
2020-02-22 03:55:22 +05:30
|
|
|
def __repr__(self):
|
|
|
|
"""Return message suitable for interactive shells."""
|
|
|
|
return srepr(self.message)
|