Skip to content

Commit 2e1b2ce

Browse files
committed
a more consistent resource_monitor checking
1 parent 5fb992e commit 2e1b2ce

File tree

7 files changed

+58
-17
lines changed

7 files changed

+58
-17
lines changed

nipype/interfaces/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,9 +1066,9 @@ def run(self, **inputs):
10661066
results : an InterfaceResult object containing a copy of the instance
10671067
that was executed, provenance information and, if successful, results
10681068
"""
1069-
from ..utils.profiler import resource_monitor, ResourceMonitor
1069+
from ..utils.profiler import ResourceMonitor
10701070

1071-
enable_rm = resource_monitor and self.resource_monitor
1071+
enable_rm = config.resource_monitor and self.resource_monitor
10721072
force_raise = not getattr(self.inputs, 'ignore_exception', False)
10731073
self.inputs.trait_set(**inputs)
10741074
self._check_mandatory_inputs()

nipype/interfaces/tests/test_resource_monitor.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,15 @@
1111
import pytest
1212

1313
# Import packages
14-
from nipype.utils.profiler import resource_monitor as run_profile, _use_resources
14+
from nipype import config
15+
from nipype.utils.profiler import _use_resources
1516
from nipype.interfaces.base import traits, CommandLine, CommandLineInputSpec
1617
from nipype.interfaces import utility as niu
1718

19+
# Try to enable the resource monitor
20+
config.enable_resource_monitor()
21+
run_profile = config.resource_monitor
22+
1823

1924
class UseResourcesInputSpec(CommandLineInputSpec):
2025
mem_gb = traits.Float(desc='Number of GB of RAM to use',

nipype/pipeline/engine/nodes.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -725,7 +725,6 @@ def update(self, **opts):
725725
self.inputs.update(**opts)
726726

727727
def write_report(self, report_type=None, cwd=None):
728-
from ...utils.profiler import resource_monitor
729728
if not str2bool(self.config['execution']['create_report']):
730729
return
731730
report_dir = op.join(cwd, '_report')
@@ -763,7 +762,7 @@ def write_report(self, report_type=None, cwd=None):
763762
rst_dict = {'hostname': self.result.runtime.hostname,
764763
'duration': self.result.runtime.duration}
765764
# Try and insert memory/threads usage if available
766-
if resource_monitor:
765+
if config.resource_monitor:
767766
rst_dict['mem_peak_gb'] = self.result.runtime.mem_peak_gb
768767
rst_dict['cpu_percent'] = self.result.runtime.cpu_percent
769768

nipype/pipeline/engine/utils.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1298,6 +1298,10 @@ def write_workflow_prov(graph, filename=None, format='all'):
12981298

12991299

13001300
def write_workflow_resources(graph, filename=None):
1301+
"""
1302+
Generate a JSON file with profiling traces that can be loaded
1303+
in a pandas DataFrame or processed with JavaScript like D3.js
1304+
"""
13011305
import simplejson as json
13021306
if not filename:
13031307
filename = os.path.join(os.getcwd(), 'resource_monitor.json')

nipype/pipeline/engine/workflows.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ def run(self, plugin=None, plugin_args=None, updatehash=False):
595595
logger.info('Provenance file prefix: %s' % prov_base)
596596
write_workflow_prov(execgraph, prov_base, format='all')
597597

598-
if str2bool(self.config['execution'].get('resource_monitor', 'false')):
598+
if config.resource_monitor:
599599
write_workflow_resources(execgraph)
600600
return execgraph
601601

nipype/utils/config.py

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@
1818
import configparser
1919
import numpy as np
2020

21-
from builtins import str, object, open
21+
from builtins import bytes, str, object, open
2222

2323
from simplejson import load, dump
24-
from ..external import portalocker
2524
from future import standard_library
25+
from ..external import portalocker
26+
from .misc import str2bool
27+
2628
standard_library.install_aliases()
2729

2830

@@ -96,6 +98,7 @@ def __init__(self, *args, **kwargs):
9698
config_file = os.path.join(config_dir, 'nipype.cfg')
9799
self.data_file = os.path.join(config_dir, 'nipype.json')
98100
self._config.readfp(StringIO(default_cfg))
101+
self._resource_monitor = None
99102
if os.path.exists(config_dir):
100103
self._config.read([config_file, 'nipype.cfg'])
101104

@@ -202,5 +205,41 @@ def enable_provenance(self):
202205
self._config.set('execution', 'write_provenance', 'true')
203206
self._config.set('execution', 'hash_method', 'content')
204207

208+
@property
209+
def resource_monitor(self):
210+
"""Check if resource_monitor is available"""
211+
if self._resource_monitor is not None:
212+
return self._resource_monitor
213+
214+
# Cache config from nipype config
215+
self.resource_monitor = self._config.get(
216+
'execution', 'resource_monitor') or False
217+
return self._resource_monitor
218+
219+
@resource_monitor.setter
220+
def resource_monitor(self, value):
221+
# Accept string true/false values
222+
if isinstance(value, (str, bytes)):
223+
value = str2bool(value.lower())
224+
225+
if value is False:
226+
self._resource_monitor = False
227+
elif value is True:
228+
if not self._resource_monitor:
229+
# Before setting self._resource_monitor check psutil availability
230+
self._resource_monitor = False
231+
try:
232+
import psutil
233+
self._resource_monitor = LooseVersion(
234+
psutil.__version__) >= LooseVersion('5.0')
235+
except ImportError:
236+
pass
237+
finally:
238+
if not self._resource_monitor:
239+
warn('Could not enable the resource monitor: psutil>=5.0'
240+
' could not be imported.')
241+
self._config.set('execution', 'resource_monitor',
242+
('%s' % self._resource_monitor).lower())
243+
205244
def enable_resource_monitor(self):
206-
self._config.set('execution', 'resource_monitor', 'true')
245+
self.resource_monitor = True

nipype/utils/profiler.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# @Author: oesteban
33
# @Date: 2017-09-21 15:50:37
44
# @Last Modified by: oesteban
5-
# @Last Modified time: 2017-09-29 16:42:27
5+
# @Last Modified time: 2017-10-02 15:44:29
66
"""
77
Utilities to keep track of performance
88
"""
@@ -17,15 +17,9 @@
1717

1818
from builtins import open, range
1919
from .. import config, logging
20-
from .misc import str2bool
2120

2221
proflogger = logging.getLogger('utils')
23-
24-
resource_monitor = str2bool(config.get('execution', 'resource_monitor', 'false'))
25-
if resource_monitor and psutil is None:
26-
proflogger.warning('Switching "resource_monitor" off: the option was on, but the '
27-
'necessary package "psutil" could not be imported.')
28-
resource_monitor = False
22+
resource_monitor = config.resource_monitor
2923

3024
# Init variables
3125
_MB = 1024.0**2

0 commit comments

Comments
 (0)