Skip to content

Commit 2da584e

Browse files
committed
small code quality fixups
1 parent d5e0692 commit 2da584e

File tree

7 files changed

+87
-45
lines changed

7 files changed

+87
-45
lines changed

pypop/dimemas.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,10 @@ def dimemas_analyse(tracefile, configfile, outpath=None, substrings=None):
9494

9595
# Make sure config._tmpdir_path exists before using it
9696
if config._tmpdir_path:
97-
try:
98-
os.makedirs(config._tmpdir_path, exist_ok=True)
99-
except OSError as err:
100-
print("FATAL: {}".format(err))
101-
workdir = mkdtemp(dir=config._tmpdir_path)
97+
os.makedirs(config._tmpdir_path, exist_ok=True)
98+
workdir = mkdtemp(dir=config._tmpdir_path)
99+
else:
100+
workdir = mkdtemp()
102101

103102
# Create temporary config from supplied config and substitution dict
104103
dimconfig = os.path.join(workdir, ".tmpconfig".join(splitext(basename(configfile))))

pypop/extrae.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from os.path import basename, dirname, normpath, splitext
1515
from tempfile import mkdtemp, mkstemp
1616
import subprocess as sp
17+
import warnings
1718

1819
from pkg_resources import resource_filename
1920

@@ -23,6 +24,8 @@
2324
from .prv import PRV, get_prv_header_info
2425
from . import config
2526

27+
from pypop.utils.exceptions import ExtraePRVNoOnOffEventsError
28+
2629
floatmatch = re.compile(r"[0-9,]+\.[0-9]+")
2730
keymatch = re.compile(r"@.*@")
2831
tabmatch = re.compile(r"\t+")
@@ -111,13 +114,14 @@ def chop_prv_to_roi(prv_file, outfile=None):
111114
if outfile:
112115
workdir = dirname(normpath(outfile))
113116
else:
114-
tgtname = ".chop".join(splitext(basename(prv_file)))
117+
if prv_file.endswith(".gz"):
118+
tgtname = ".chop".join(splitext(basename(prv_file[:-3])))
119+
else:
120+
tgtname = ".chop".join(splitext(basename(prv_file)))
121+
115122
# Make sure config._tmpdir_path exists before using it
116123
if config._tmpdir_path:
117-
try:
118-
os.makedirs(config._tmpdir_path, exist_ok=True)
119-
except OSError as err:
120-
print("FATAL: {}".format(err))
124+
os.makedirs(config._tmpdir_path, exist_ok=True)
121125
workdir = mkdtemp(dir=config._tmpdir_path)
122126
outfile = os.path.join(workdir, tgtname)
123127

@@ -189,7 +193,7 @@ def chop_prv_to_roi(prv_file, outfile=None):
189193

190194

191195
def _get_roi_times(roi_prv):
192-
""" Extract ROi timing information from a filtered trace
196+
""" Extract ROI timing information from a filtered trace
193197
194198
Expects a trace containing only Extrae On/Off events and returns tuple of
195199
earliest and latest time
@@ -211,7 +215,7 @@ def _get_roi_times(roi_prv):
211215
ontime, offtime = (ons["time"].min(), 1 + offs["time"].max())
212216

213217
if ontime is numpy.nan or offtime is numpy.nan:
214-
raise ValueError("Unable to locate valid ON-OFF bracket in trace")
218+
raise ExtraePRVNoOnOffEventsError("No valid Extrae ON-OFF bracket in trace")
215219

216220
return ontime, offtime
217221

@@ -389,12 +393,10 @@ def run_paramedir(tracefile, paramedir_config, outfile=None, variables=None):
389393

390394
# Make sure config._tmpdir_path exists before using it
391395
if config._tmpdir_path:
392-
try:
393-
os.makedirs(config._tmpdir_path, exist_ok=True)
394-
except OSError as err:
395-
print("FATAL: {}".format(err))
396-
397-
tmpdir = mkdtemp(dir=config._tmpdir_path)
396+
os.makedirs(config._tmpdir_path, exist_ok=True)
397+
tmpdir = mkdtemp(dir=config._tmpdir_path)
398+
else:
399+
tmpdir = mkdtemp()
398400

399401
# If variables is none, still sub with empty dict
400402
variables = variables if variables else {}
@@ -476,7 +478,7 @@ def _split_countline(countline, bins):
476478
extra_strings = len(count_strings) - num_values
477479

478480
if extra_strings > 1:
479-
print(
481+
warnings.warn(
480482
"Warning, got more label strings ({}) than expected (1)"
481483
"".format(extra_strings)
482484
)

pypop/notebook_interface/fileselector.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
# SPDX-License-Identifier: BSD-3-Clause-Clear
33
# Copyright (c) 2019, The Numerical Algorithms Group, Ltd. All rights reserved.
44

5+
from os import getcwd
56
from os.path import expanduser, normpath
67

8+
from ipyfilechooser import FileChooser
79
from ipywidgets import (
810
Accordion,
911
Box,
@@ -15,21 +17,26 @@
1517
Layout,
1618
Label,
1719
)
18-
from ipyfilechooser import FileChooser
1920

2021

2122
class ValidatingChooser(VBox):
2223

2324
_container_layout = Layout(margin="1em 0em 1em 0em")
2425
_msgbox_layout = Layout()
2526

26-
def __init__(self, starting_file=None, **kwargs):
27+
def __init__(self, starting_file=None, starting_path=None, **kwargs):
2728

2829
if starting_file is None:
2930
starting_file = ""
3031

32+
if starting_path is None:
33+
starting_path = getcwd()
34+
3135
self._filechooser = FileChooser(
32-
filename=starting_file, select_default=bool(starting_file),
36+
filename=starting_file,
37+
path=starting_path,
38+
select_default=bool(starting_file),
39+
use_dir_icons=True,
3340
)
3441
self._msgbox = HBox(children=[], layout=self._msgbox_layout)
3542
self._validity = None
@@ -129,6 +136,10 @@ def _create_buttons(self):
129136
)
130137

131138
def _create_advanced_config_box(self):
139+
self._advanced_config_controls["Chop to ROI"] = Checkbox(
140+
value=True, description="Chop to ROI"
141+
)
142+
132143
self._advanced_config_controls["Delete Cache"] = Checkbox(
133144
value=False, description="Delete Cache"
134145
)
@@ -148,7 +159,9 @@ def _add_filechooser_row(self, callback_reference=None):
148159
def _create_filechoosers(self):
149160

150161
self._filechoosers = [
151-
ValidatingChooser(starting_file=fname) if fname else ValidatingChooser()
162+
ValidatingChooser(starting_file=fname)
163+
if fname
164+
else ValidatingChooser(starting_path=self._base_dir)
152165
for fname in self._files
153166
]
154167
[fc.set_file_select_callback(self._update_files) for fc in self._filechoosers]

pypop/notebook_interface/wizard.py

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# SPDX-License-Identifier: BSD-3-Clause-Clear
33
# Copyright (c) 2019, The Numerical Algorithms Group, Ltd. All rights reserved.
44

5-
from ipywidgets import Tab, Layout
5+
from ipywidgets import Tab, Layout, VBox, Text
66

77
import pypop.metrics.metricset as pm
88
from ..traceset import TraceSet
@@ -11,6 +11,7 @@
1111
from .bokeh_widget import BokehWidgetWrapper
1212
from .reporting import ReportGenerator
1313

14+
from pypop.utils.exceptions import ExtraePRVNoOnOffEventsError
1415

1516
class TypeAsserter:
1617

@@ -113,18 +114,21 @@ def __init__(self, metric_calc="auto", base_dir=".", starting_files=None, **kwar
113114
self._scaling_plot = None
114115
self._report_generator = None
115116
self._metric_calculator = metric_calc
117+
self._base_dir = base_dir
116118

117119
self._analysis_state = AnalysisState()
118120

119121
self._fileselector = FileSelector(
120-
base_dir=base_dir,
122+
base_dir=self._base_dir,
121123
starting_files=starting_files,
122124
calculation_callback=self._calculate_callback_hook,
123125
analysis_state=self._analysis_state,
124126
)
125127

128+
self._status_box = VBox()
129+
126130
super().__init__(
127-
children=[self._fileselector],
131+
children=[VBox([self._status_box, self._fileselector])],
128132
layout=Layout(width="auto", max_width="1280px"),
129133
**kwargs
130134
)
@@ -133,9 +137,23 @@ def __init__(self, metric_calc="auto", base_dir=".", starting_files=None, **kwar
133137

134138
def _calculate_callback_hook(self, callback_reference=None):
135139

136-
statistics = TraceSet(
137-
self._fileselector.filenames, force_recalculation=False, chop_to_roi=True
138-
)
140+
advanced_config = self._fileselector._advanced_config_controls
141+
142+
try:
143+
statistics = TraceSet(
144+
self._fileselector.filenames,
145+
force_recalculation=advanced_config["Delete Cache"].value,
146+
chop_to_roi=advanced_config["Chop to ROI"].value
147+
)
148+
except ExtraePRVNoOnOffEventsError as err:
149+
warnstr = "Warning: Disabling Chopping to ROI ({})".format(err)
150+
self._status_box.children = [Text(warnstr, layout=Layout(width='auto'))]
151+
statistics = TraceSet(
152+
self._fileselector.filenames,
153+
force_recalculation=advanced_config["Delete Cache"].value,
154+
chop_to_roi=False,
155+
)
156+
139157
if self._metric_calculator in ("auto", None):
140158
self._metric_calculate = statistics.suggested_metrics
141159

pypop/prv.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -85,21 +85,24 @@ class PRV:
8585

8686
def __init__(self, prv_path):
8787

88-
if prv_path and prv_path.endswith((".prv", ".prv.gz")):
89-
self._event_names = {}
90-
self._event_vals = {}
91-
self._parse_pcf(prv_path)
92-
93-
self._parse_prv(prv_path)
88+
try:
89+
self._load_prv_and_pcf(prv_path)
9490

95-
else:
91+
except ValueError:
9692
try:
9793
self._load_pickle(prv_path)
9894
except ValueError:
9995
raise ValueError("Not a prv or valid pickle")
10096

10197
self._omp_region_data = None
10298

99+
def _load_prv_and_pcf(self, prv_path):
100+
self._event_names = {}
101+
self._event_vals = {}
102+
self._parse_pcf(prv_path)
103+
104+
self._parse_prv(prv_path)
105+
103106
def _parse_pcf(self, prv_path):
104107

105108
if prv_path.endswith(".gz"):
@@ -199,10 +202,16 @@ def save(self, filename):
199202
pickle.dump(savedata, fh)
200203

201204
def _load_pickle(self, filename):
202-
with gzip.open(filename, "rb") as fh:
203-
data = pickle.load(fh)
204-
205205
try:
206+
with gzip.open(filename, "rb") as fh:
207+
data = pickle.load(fh)
208+
except gzip.BadGzipFile:
209+
try:
210+
with open(filename, "rb") as fh:
211+
data = pickle.load(fh)
212+
except pickle.UnpicklingError:
213+
raise ValueError("Invalid pickle -- missing data")
214+
206215
self.metadata, self.state, self.event, self.comm = data
207216
except ValueError:
208217
raise ValueError("Invalid pickle -- missing data")
@@ -543,7 +552,7 @@ def _parse_paraver_headerline(headerline):
543552
_format_timing(elems[1]),
544553
*_split_nodestring(elems[2]),
545554
_format_num_apps(elems[3]),
546-
_format_app_list(elems[4])
555+
_format_app_list(elems[4]),
547556
)
548557

549558
return metadata

pypop/trace/prvtrace.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,18 +144,15 @@ def _split_layoutstring(prv_td):
144144
@staticmethod
145145
def _analyze_tracefile(trace, chop_to_roi, outpath):
146146
if outpath:
147-
try:
148-
makedirs(outpath, exist_ok=True)
149-
except OSError as err:
150-
print("Fatal: {}".format(err))
147+
makedirs(outpath, exist_ok=True)
151148

152149
if chop_to_roi:
153150
if outpath:
154151
tgtname = ".chop".join(splitext(basename(trace)))
155152
outfile = path_join(outpath, tgtname)
156153
else:
157154
outfile = None
158-
cut_trace = chop_prv_to_roi(trace, outfile)
155+
cut_trace = chop_prv_to_roi(trace, outfile)
159156
else:
160157
cut_trace = trace
161158

pypop/utils/exceptions.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,7 @@ class WrongLoaderError(RuntimeError):
77

88
class UnknownLoaderError(RuntimeError):
99
pass
10+
11+
12+
class ExtraePRVNoOnOffEventsError(RuntimeError):
13+
pass

0 commit comments

Comments
 (0)