Skip to content

Commit 5cddbf3

Browse files
committed
Merge branch '372-silent-library' into 'development'
logging allows users to conveniently silence info output when running scripts with the library Closes #372 See merge request damask/DAMASK!1024
2 parents 557ea2d + 9176920 commit 5cddbf3

File tree

8 files changed

+37
-17
lines changed

8 files changed

+37
-17
lines changed

python/damask/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010

1111
from pathlib import Path as _Path
1212
import re as _re
13+
import logging
14+
15+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
1316

1417
name = 'damask'
1518
with open(_Path(__file__).parent/_Path('VERSION')) as _f:

python/damask/_configmaterial.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@
22

33
import numpy as np
44
import h5py
5+
import logging
56

6-
from ._typehints import FloatSequence, StrSequence
77
from . import YAML
88
from . import Rotation
99
from . import Orientation
1010
from . import util
1111
from . import tensor
1212
from . import Table
13+
from ._typehints import FloatSequence, StrSequence
14+
1315

16+
logger = logging.getLogger(__name__)
1417

1518
class ConfigMaterial(YAML):
1619
"""
@@ -312,7 +315,7 @@ def LabeledList(label,items):
312315
msg.append(f'{LabeledList(v,_empty)} undefined')
313316
ok = False
314317

315-
print(util.srepr(msg))
318+
logger.info(util.srepr(msg))
316319
return ok
317320

318321

@@ -339,7 +342,7 @@ def is_valid(self) -> bool:
339342
try:
340343
Orientation(lattice=v['lattice'])
341344
except KeyError:
342-
print(f"Invalid lattice '{v['lattice']}' in phase '{k}'")
345+
logger.warning(f"Invalid lattice '{v['lattice']}' in phase '{k}'")
343346
ok = False
344347

345348
if 'material' in self:
@@ -352,10 +355,10 @@ def is_valid(self) -> bool:
352355
try:
353356
Rotation.from_quaternion(c['O'])
354357
except ValueError:
355-
print(f"Invalid orientation '{c['O']}' in material '{i}'")
358+
logger.warning(f"Invalid orientation '{c['O']}' in material '{i}'")
356359
ok = False
357360
if not np.isclose(v,1.0):
358-
print(f"Total fraction v = {v} ≠ 1 in material '{i}'")
361+
logger.warning(f"Total fraction v = {v} ≠ 1 in material '{i}'")
359362
ok = False
360363

361364
return ok

python/damask/_geomgrid.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@
2222
except ImportError:
2323
nb = False
2424

25+
2526
def numba_njit_wrapper(**kwargs):
2627
return (lambda function: nb.njit(function) if nb else function)
2728

28-
2929
class GeomGrid:
3030
"""
3131
Geometry definition for grid solvers.

python/damask/_result.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import numpy as np
1515
from numpy import ma
1616
from scipy import interpolate
17+
import logging
1718

1819
import damask
1920
from . import VTK
@@ -26,6 +27,8 @@
2627
from ._typehints import FloatSequence, IntSequence, DADF5Dataset, BravaisLattice
2728

2829

30+
logger = logging.getLogger(__name__)
31+
2932
chunk_size = 1024**2//8 # for compression in HDF5
3033

3134
prefix_inc = 'increment_'
@@ -358,7 +361,7 @@ def view(self,*,
358361
dup = self._manage_view('set',increments,times,phases,homogenizations,fields)
359362
if protected is not None:
360363
if not protected:
361-
print(util.warn('Warning: Modification of existing datasets allowed!'))
364+
logger.warning(util.warn('Modification of existing datasets allowed!'))
362365
dup._protected = protected
363366

364367
return dup
@@ -572,7 +575,7 @@ def list_data(self) -> List[str]:
572575
def enable_user_function(self,
573576
func: Callable):
574577
globals()[func.__name__]=func
575-
print(f'Function {func.__name__} enabled in add_calculation.')
578+
logger.info(f'Function {func.__name__} enabled in add_calculation.')
576579

577580

578581
@property
@@ -1539,7 +1542,7 @@ def job_pointwise(group: str,
15391542
'meta': {k: v for k,v in loc.attrs.items()}}
15401543
return callback(**datasets_in,**args)
15411544
except Exception as err:
1542-
print(f'Error during calculation: {err}.')
1545+
logger.error(f'Error during pointwise calculation: {err}.')
15431546
return None
15441547

15451548
groups = []
@@ -1552,7 +1555,7 @@ def job_pointwise(group: str,
15521555
if set(datasets.values()).issubset(f[group].keys()): groups.append(group)
15531556

15541557
if len(groups) == 0:
1555-
print('No matching dataset found, no data was added.')
1558+
logger.warning('No matching dataset found, no data was added.')
15561559
return
15571560

15581561

@@ -1585,7 +1588,7 @@ def job_pointwise(group: str,
15851588
dataset.attrs['creator'] = f'damask.Result.{creator} v{damask.version}'
15861589

15871590
except (OSError,RuntimeError) as err:
1588-
print(f'Could not add dataset: {err}.')
1591+
logger.error(f'Could not add dataset: {err}.')
15891592

15901593

15911594
def _mappings(self) -> MappingsTuple:

python/damask/_table.py

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from ._typehints import FileHandle
99
from . import util
1010

11+
1112
class Table:
1213
"""Manipulate multi-dimensional spreadsheet-like data."""
1314

python/damask/_vtk.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import multiprocessing as mp
33
from pathlib import Path
4+
import logging
45
from typing import Optional, Union, Literal, List, Sequence
56

67
import numpy as np
@@ -62,6 +63,8 @@
6263
from . import Colormap
6364

6465

66+
logger = logging.getLogger(__name__)
67+
6568
class VTK:
6669
"""
6770
Spatial visualization (and potentially manipulation).
@@ -685,7 +688,7 @@ def show(self,
685688
iren = vtkRenderWindowInteractor()
686689
iren.SetRenderWindow(window)
687690
if os.name == 'posix' and 'DISPLAY' not in os.environ:
688-
print('Found no rendering device')
691+
logger.warning('Found no rendering device')
689692
else:
690693
window.Render()
691694
iren.Start()

python/damask/solver/_marc.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@
22
import shlex
33
import re
44
from pathlib import Path
5+
import logging
56
from typing import Literal
67

8+
9+
logger = logging.getLogger(__name__)
10+
711
_marc_version = '2024.1'
812
_marc_root = '/opt/msc'
913
_damask_root = str(Path(__file__).parents[3])
@@ -92,7 +96,7 @@ def submit_job(self, model: str, job: str,
9296
f'-nprocd {domains} -nsolver {domains} -nthread_elem {domains} -nthread_solver {domains} ')\
9397
+ '-autorst 0 -ci n -cr n -dcoup 0 -b no -v no '\
9498
+ (f'-u {usersub} -save y' if compile else f'-prog {usersub.with_suffix("")}')
95-
print(cmd)
99+
logger.info(cmd)
96100

97101
ret = subprocess.run(shlex.split(cmd),capture_output=True,env=env)
98102

python/damask/util.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212
from collections import abc as _abc, OrderedDict as _OrderedDict
1313
from functools import reduce as _reduce, partial as _partial, wraps as _wraps
1414
import inspect
15+
from pathlib import Path as _Path
16+
import logging
1517
from typing import Optional as _Optional, Callable as _Callable, Union as _Union, Iterable as _Iterable, \
1618
Dict as _Dict, List as _List, Tuple as _Tuple, Literal as _Literal, NamedTuple as _NamedTuple, \
1719
Any as _Any, TextIO as _TextIO, Generator as _Generator
18-
from pathlib import Path as _Path
1920

2021
import numpy as _np
2122
import h5py as _h5py
@@ -29,6 +30,8 @@ class stdioTuple(_NamedTuple):
2930
stdout: str
3031

3132

33+
logger = logging.getLogger(__name__)
34+
3235
# https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
3336
# https://stackoverflow.com/questions/287871
3437
_colors = {
@@ -177,7 +180,7 @@ def pass_signal(sig,_,proc,default):
177180

178181
signals = [_signal.SIGINT,_signal.SIGTERM]
179182

180-
print(f"running '{cmd}' in '{wd}'")
183+
logger.info(f"running '{cmd}' in '{wd}'")
181184
process = _subprocess.Popen(_shlex.split(cmd),
182185
stdout = _subprocess.PIPE,
183186
stderr = _subprocess.PIPE,
@@ -194,8 +197,8 @@ def pass_signal(sig,_,proc,default):
194197
_signal.signal(sig,state)
195198

196199
if process.returncode != 0:
197-
print(stdout)
198-
print(stderr)
200+
logger.error(stdout)
201+
logger.error(stderr)
199202
raise RuntimeError(f"'{cmd}' failed with returncode {process.returncode}")
200203

201204
return stdioTuple(stdout, stderr)

0 commit comments

Comments
 (0)