-
Notifications
You must be signed in to change notification settings - Fork 240
/
iprof_utils.py
333 lines (287 loc) · 11.4 KB
/
iprof_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import os
import sys
import ast
from inspect import getmembers
from fnmatch import fnmatchcase
from collections import defaultdict
class _Options(object):
"""
A fake options class for use when there is no parser.
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __getattr__(self, name):
return None
class FunctionFinder(ast.NodeVisitor):
"""
This class locates all of the functions and methods in a file and associates any
method with its corresponding class.
"""
def __init__(self, fname, cache):
ast.NodeVisitor.__init__(self)
self.fname = fname
self.cache = cache
self.stack = []
def _do_callable_def(self, node):
if self.stack:
qual = (None, '.'.join(self.stack), node.name)
else:
qual = ("<%s:%d>" % (self.fname, node.lineno), None, node.name)
self.cache[node.lineno] = qual
# some versions of python report different line numbers for funnctions/classes with
# decorators, so just put keys in the cache dict for all of the decorator line numbers
# as well in order to avoid any KeyErrors.
for d in node.decorator_list:
self.cache[d.lineno] = qual
self.stack.append(node.name)
for bnode in node.body:
self.visit(bnode)
self.stack.pop()
def visit_ClassDef(self, node):
self._do_callable_def(node)
def visit_FunctionDef(self, node):
self._do_callable_def(node)
def find_qualified_name(filename, line, cache, full=True):
"""
Determine full function name (class.method) or function for unbound functions.
Parameters
----------
filename : str
Name of file containing source code.
line : int
Line number within the given file.
cache : dict
A dictionary containing infomation by filename.
full : bool
If True, assemble the full name else return the parts
Returns
-------
str or None
Fully qualified function/method name or None.
"""
if filename not in cache:
fcache = {}
with open(filename, 'Ur') as f:
contents = f.read()
if len(contents) > 0 and contents[-1] != '\n':
contents += '\n'
FunctionFinder(filename, fcache).visit(ast.parse(contents, filename))
cache[filename] = fcache
if full:
parts = cache[filename][line]
if parts[0]:
return '.'.join((parts[0], parts[2]))
else:
return '.'.join((parts[1], parts[2]))
return cache[filename][line]
# This maps a simple identifier to a group of classes and corresponding
# glob patterns for each class.
func_group = {}
base_classes = {}
def _setup_func_group():
global func_group, base_classes
from openmdao.core.system import System
from openmdao.core.component import Component
from openmdao.core.explicitcomponent import ExplicitComponent
from openmdao.core.problem import Problem
from openmdao.core.driver import Driver
from openmdao.core.total_jac import _TotalJacInfo
from openmdao.solvers.solver import Solver, LinearSolver
from openmdao.solvers.nonlinear.newton import NewtonSolver
from openmdao.solvers.linear.direct import DirectSolver
from openmdao.jacobians.jacobian import Jacobian
from openmdao.matrices.matrix import Matrix
from openmdao.vectors.default_vector import DefaultVector, DefaultTransfer
from openmdao.approximation_schemes.approximation_scheme import ApproximationScheme
for class_ in [System, ExplicitComponent, Problem, Driver, _TotalJacInfo, Solver, LinearSolver,
NewtonSolver, Jacobian, Matrix, DefaultVector, DefaultTransfer]:
base_classes[class_.__name__] = class_
func_group.update({
'openmdao': [
("*", (System, Jacobian, Matrix, Solver, Driver, Problem)),
],
'openmdao_all': [
("*", (System, DefaultVector, DefaultTransfer, Jacobian, Matrix, Solver, Driver,
Problem, _TotalJacInfo)),
],
'setup': [
("__init__", (System, Solver, Driver, Problem, Jacobian, DefaultVector, _TotalJacInfo,
Matrix)),
("*setup*", (System, Solver, Driver, Problem, Jacobian, DefaultVector, _TotalJacInfo,
Matrix)),
('_configure', (System,)),
('set_initial_values', (System,)),
('_set_initial_conditions', (Problem,)),
('_build', (Matrix,)),
('_add_submat', (Matrix,)),
('_get_promotion_maps', (System,)),
('_set_approx_partials_meta', (System,)),
('_init_relevance', (System,)),
('_get_initial_*', (System,)),
('_initialize_*', (DefaultVector,)),
('_create_*', (DefaultVector,)),
('_extract_root_data', (DefaultVector,)),
],
'dataflow': [
('*compute*', (System,)),
('*linear*', (System,)),
('_transfer', (System,)),
('*', (DefaultTransfer,)),
],
'linear': [
('_apply_linear', (System,)),
('_setup_jacobians', (System, Solver)),
('_solve_linear', (System,)),
('apply_linear', (System,)),
('solve_linear', (System,)),
('_set_approx_partials_meta', (System, Jacobian)),
('_linearize', (System, Solver)),
# include NewtonSolver to provide some context
('solve', (LinearSolver, NewtonSolver)),
('_update', (Jacobian,)),
('_apply', (Jacobian,)),
('_initialize', (Jacobian,)),
('compute_totals', (_TotalJacInfo, Problem, Driver)),
('compute_totals_approx', (_TotalJacInfo,)),
('compute_jacvec_product', (System,)),
],
'jac': [
('_linearize', (System, DirectSolver)),
('_setup_jacobians', (System,)),
('compute_totals', (_TotalJacInfo, Problem, Driver)),
('compute_totals_approx', (_TotalJacInfo,)),
('_apply_linear', (System,)),
('solve', (LinearSolver, NewtonSolver)),
('_update', (Jacobian,)),
('_initialize', (Jacobian,)),
],
'solver': [
('*', (Solver,))
],
'driver': [
('*', (Driver,))
],
'transfer': [
('*', (DefaultTransfer,)),
('_transfer', (System,))
],
'coloring': [
('*_approx_*', (Driver, System)),
('*color*', (object,)),
('*partials*', (System, Driver)),
('*sparsity*', (Jacobian, System, Driver)),
('*simul*', (Driver, System)),
('*jacobian*', (Driver, System)),
('_setup', (System,)),
('_final_setup', (System,)),
]
# NOTE: context managers and other functions that yield instead of return will NOT show
# up properly in the trace. For example, our context managers for scaling will show up
# as a call and immediate return from the context manager, followed by the functions that
# should show up as inside of the context manager but don't. This is just here to
# remind me not to try to create a 'scaling' group again.
# 'scaling': [
# ('*scaled_context*', (System,)),
# ('compute*', (Component, ApproximationScheme)),
# ('_solve*', (System,)),
# ('solve_*', (System,)),
# ('run_*', (System,)),
# ('guess_*', (System,)),
# ('*apply*', (System,)),
# ('_apply', (Jacobian,)),
# ('*linearize', (System,)),
# ],
})
try:
from mpi4py import MPI
from petsc4py import PETSc
from openmdao.vectors.petsc_vector import PETScVector, PETScTransfer
#TODO: this needs work. Still lots of MPI calls not covered here...
func_group['mpi'] = [
('*', (PETScTransfer,)),
('get_norm', (PETScVector,)),
('_initialize_data', (PETScVector,))
]
except ImportError:
pass
def _collect_methods(method_patterns=None):
"""
Iterate over a dict of method name patterns mapped to classes. Search
through the classes for anything that matches and return a dict of
exact name matches and their corresponding classes.
Parameters
----------
method_patterns : [(pattern1, (class1, class2, ... class_n)), ... (pattern_n, (class_n1, class_n2, ...)]
List of tuples of glob patterns and lists of classes used for isinstance checks
Returns
-------
defaultdict
Dict of method names and tuples of all classes that matched for that method. Default value
of the dict is a class that matches nothing
"""
if method_patterns is None:
return None
matches = defaultdict(list)
# TODO: update this to also work with stand-alone functions
for pattern, classes in method_patterns:
for class_ in classes:
for name, obj in getmembers(class_):
if callable(obj) and (pattern == '*' or fnmatchcase(name, pattern)):
matches[name].append(class_)
# convert values to tuples so we can use in isinstance call
for name in matches:
lst = matches[name]
if len(lst) == 1:
matches[name] = lst[0]
else:
matches[name] = tuple(lst)
return matches
def _create_profile_callback(stack, matches=None, do_call=None, do_ret=None, context=None,
filters=None):
"""
The wrapped function returned from here handles identification of matching calls when called
as a setprofile callback.
"""
if filters:
newfilts = []
for s in filters:
class_name, filt = s.split(' ', 1)
class_ = base_classes[class_name]
newfilts.append((class_, compile(filt, mode='eval', filename=filt)))
filters = newfilts
def _wrapped(frame, event, arg):
if event == 'call':
if matches is None:
stack.append(id(frame))
if do_call is not None:
return do_call(frame, arg, stack, context)
elif 'self' in frame.f_locals and frame.f_code.co_name in matches and \
isinstance(frame.f_locals['self'], matches[frame.f_code.co_name]):
pred = True
if filters:
inst = frame.f_locals['self']
for class_, filt in filters:
if isinstance(inst, class_):
pred = eval(filt, globals(), frame.f_locals) # nosec: internal use
break
if pred:
stack.append(id(frame))
if do_call is not None:
return do_call(frame, arg, stack, context)
elif event == 'return' and stack:
if id(frame) == stack[-1]:
stack.pop()
if do_ret is not None:
do_ret(frame, arg, stack, context)
return _wrapped
def _get_methods(options, default):
if options.methods is None:
methods = func_group[default]
elif isinstance(options.methods, str):
try:
methods = func_group[options.methods]
except KeyError:
raise KeyError("Unknown function group '%s'." % options.methods)
else:
methods = options.methods
return methods