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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
|
#!/usr/bin/env python3
import json
import numpy as np
import os
import re
import logging
from contextlib import contextmanager
from sklearn.metrics import r2_score
logger = logging.getLogger(__name__)
@contextmanager
def cd(path):
old_dir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(old_dir)
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
def running_mean(x: np.ndarray, N: int) -> np.ndarray:
"""
Compute `N` elements wide running average over `x`.
:param x: 1-Dimensional NumPy array
:param N: how many items to average
"""
# FIXME np.insert(x, 0, [x[0] for i in range(N/2)])
# FIXME np.insert(x, -1, [x[-1] for i in range(N/2)])
# (dabei ungerade N beachten)
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[N:] - cumsum[:-N]) / N
def human_readable(value, unit):
for prefix, factor in (
("p", 1e-12),
("n", 1e-9),
("µ", 1e-6),
("m", 1e-3),
("", 1),
("k", 1e3),
):
if value < 1e3 * factor:
return "{:.2f} {}{}".format(value * (1 / factor), prefix, unit)
return "{:.2f} {}".format(value, unit)
def is_numeric(n):
"""Check if `n` is numeric (i.e., it can be converted to float)."""
if n is None:
return False
try:
float(n)
return True
except ValueError:
return False
def is_power_of_two(n):
"""Check if `n` is a power of two (1, 2, 4, 8, 16, ...)."""
return n > 0 and (n & (n - 1)) == 0
def float_or_nan(n):
"""Convert `n` to float (if numeric) or NaN."""
if n is None:
return np.nan
try:
return float(n)
except ValueError:
return np.nan
def soft_cast_int(n):
"""
Convert `n` to int (if numeric) or return it as-is.
If `n` is empty, returns None.
If `n` is not numeric, it is left unchanged.
"""
if n is None or n == "":
return None
try:
return int(n)
except ValueError:
return n
def soft_cast_float(n):
"""
Convert `n` to float (if numeric) or return it as-is.
If `n` is empty, returns None.
If `n` is not numeric, it is left unchanged.
"""
if n is None or n == "":
return None
try:
return float(n)
except ValueError:
return n
def flatten(somelist):
"""
Flatten a list.
Example: flatten([[1, 2], [3], [4, 5]]) -> [1, 2, 3, 4, 5]
"""
return [item for sublist in somelist for item in sublist]
def parse_conf_str(conf_str):
"""
Parse a configuration string `k1=v1,k2=v2`... and return a dict `{'k1': v1, 'k2': v2}`...
Values are casted to float if possible and kept as-is otherwise.
"""
conf_dict = dict()
for option in conf_str.split(","):
key, value = option.split("=")
conf_dict[key] = soft_cast_float(value)
return conf_dict
def remove_index_from_tuple(parameters, index):
"""
Remove the element at `index` from tuple `parameters`.
:param parameters: tuple
:param index: index of element which is to be removed
:returns: parameters tuple without the element at index
"""
return (*parameters[:index], *parameters[index + 1 :])
def param_slice_eq(a, b, index):
"""
Check if by_param keys a and b are identical, ignoring the parameter at index.
parameters:
a, b -- (state/transition name, [parameter0 value, parameter1 value, ...])
index -- parameter index to ignore (0 -> parameter0, 1 -> parameter1, etc.)
Returns True iff a and b have the same state/transition name, and all
parameters at positions != index are identical.
example:
('foo', [1, 4]), ('foo', [2, 4]), 0 -> True
('foo', [1, 4]), ('foo', [2, 4]), 1 -> False
"""
if (*a[:index], *a[index + 1 :]) == (*b[:index], *b[index + 1 :]):
return True
return False
def match_parameter_values(input_param: dict, match_param: dict):
"""
Check whether one of the paramaters in `input_param` has the same value in `match_param`.
:param input_param: parameter dict of a state/transition/... measurement
:param match_param: parameter value filter
:returns: True if for all parameters k in match_param: input_param[k] == match_param[k], or if match_param is None.
"""
if match_param is None:
return True
for k, v in match_param.items():
if k in input_param and input_param[k] != v:
return False
return True
def partition_by_param(data, param_values, ignore_parameters=list()):
ret = dict()
for i, parameters in enumerate(param_values):
# ensure that parameters[param_index] = None does not affect the "param_values" entries passed to this function
parameters = list(parameters)
for param_index in ignore_parameters:
parameters[param_index] = None
param_key = tuple(parameters)
if param_key not in ret:
ret[param_key] = list()
ret[param_key].append(data[i])
return ret
def param_to_ndarray(
param_tuples, with_nan=True, categorial_to_scalar=False, ignore_indexes=list()
):
has_nan = dict()
has_non_numeric = dict()
distinct_values = dict()
category_to_scalar = dict()
for param_tuple in param_tuples:
for i, param in enumerate(param_tuple):
if not is_numeric(param):
if param is None:
has_nan[i] = True
else:
has_non_numeric[i] = True
if categorial_to_scalar and param is not None:
if not i in distinct_values:
distinct_values[i] = set()
distinct_values[i].add(param)
for i, paramset in distinct_values.items():
distinct_values[i] = sorted(paramset)
category_to_scalar[i] = dict()
for j, param in enumerate(distinct_values[i]):
category_to_scalar[i][param] = j
ignore_index = dict()
for i in range(len(param_tuples[0])):
if has_non_numeric.get(i, False) and not categorial_to_scalar:
ignore_index[i] = True
elif not with_nan and has_nan.get(i, False):
ignore_index[i] = True
else:
ignore_index[i] = False
for i in ignore_indexes:
ignore_index[i] = True
ret_tuples = list()
for param_tuple in param_tuples:
ret_tuple = list()
for i, param in enumerate(param_tuple):
if not ignore_index[i]:
if i in category_to_scalar and not is_numeric(param):
ret_tuple.append(category_to_scalar[i][param])
elif categorial_to_scalar:
ret_tuple.append(soft_cast_int(param))
else:
ret_tuple.append(param)
ret_tuples.append(ret_tuple)
return np.asarray(ret_tuples), category_to_scalar, ignore_index
def param_dict_to_list(param_dict, parameter_names, default=None):
"""
Convert {"foo": 1, "bar": 2}, ["bar", "foo", "quux"] to [2, 1, None]
"""
ret = list()
for parameter_name in parameter_names:
ret.append(param_dict.get(parameter_name, None))
return ret
def observations_enum_to_bool(observations: list, kconfig=False):
"""
Convert enum / categorial observations to boolean-only ones.
'observations' is altered in-place.
DEPRECATED.
"""
distinct_param_values = dict()
replace_map = dict()
for observation in observations:
for k, v in observation["param"].items():
if not k in distinct_param_values:
distinct_param_values[k] = set()
if v is not None:
distinct_param_values[k].add(v)
for param_name, distinct_values in distinct_param_values.items():
if len(distinct_values) > 2 and not all(
map(lambda x: x is None or is_numeric(x), distinct_values)
):
replace_map[param_name] = distinct_values
for observation in observations:
binary_keys = set()
for k, v in replace_map.items():
enum_value = observation["param"].pop(k)
for binary_key in v:
if kconfig:
if enum_value == binary_key:
observation["param"][binary_key] = "y"
else:
observation["param"][binary_key] = "n"
else:
observation["param"][binary_key] = int(enum_value == binary_key)
if binary_key in binary_keys:
print(f"Error: key '{binary_key}' is not unique")
binary_keys.add(binary_key)
def ignore_param(by_name: dict, parameter_names: list, ignored_parameters: list):
ignored_indexes = list()
unpoppable_params = list()
for param_name in sorted(ignored_parameters):
try:
ignored_indexes.append(parameter_names.index(param_name))
except ValueError:
unpoppable_params.append(param_name)
assert ignored_indexes == sorted(ignored_indexes)
ignored_indexes = sorted(ignored_indexes, reverse=True)
for name in by_name:
for param in by_name[name]["param"]:
for ignored_index in ignored_indexes:
param.pop(ignored_index)
for ignored_index in ignored_indexes:
parameter_names.pop(ignored_index)
if unpoppable_params:
logger.info(
f"ignore_param: Parameters {unpoppable_params} were not part of the observations to begin with"
)
def observation_dict_to_by_name(observation):
parameter_names = observation["param_names"]
by_name = observation["by_name"]
assert parameter_names == sorted(parameter_names)
for name in by_name:
for entry in by_name[name]["param"]:
assert len(entry) == len(parameter_names)
for attribute in by_name[name]["attributes"]:
by_name[name][attribute] = np.array(by_name[name][attribute])
return by_name, parameter_names
def observations_to_by_name(observations):
"""
Convert observation list to by_name dictionary for AnalyticModel analysis
:param observations: list of dicts, each representing one measurement. dict keys:
"name": name of observed state/transition/...
"param": {"parameter name": parameter value, ...},
"attribute:" {"attribute name": attribute value, ...}
:param attributes: observed attributes (i.e., actual measurements). Each measurement dict must have an
entry holding the data value for each attribute. It should not be None.
:returns: tuple (by_name, parameter_names) which can be passed to AnalyticModel
"""
if type(observations) is dict:
return observation_dict_to_by_name(observations)
parameter_names = set()
attributes_by_name = dict()
by_name = dict()
for observation in observations:
if observation["name"] not in attributes_by_name:
attributes_by_name[observation["name"]] = set()
parameter_names.update(observation["param"].keys())
attributes_by_name[observation["name"]].update(observation["attribute"].keys())
name = observation["name"]
if name not in by_name:
attributes = list(attributes_by_name[observation["name"]])
by_name[name] = {"attributes": attributes, "param": list()}
for attribute in attributes:
by_name[name][attribute] = list()
parameter_names = sorted(parameter_names)
for observation in observations:
name = observation["name"]
by_name[name]["param"].append(
param_dict_to_list(observation["param"], parameter_names)
)
for attribute in attributes_by_name[name]:
if attribute not in observation["attribute"]:
raise ValueError(
f"""Attribute "{attribute}" missing in observation "{name}". Parameters = {observation["param"]}"""
)
if observation["attribute"][attribute] is None:
raise ValueError(
f"""Attribute "{attribute}" of observation "{name}" is None. This is not allowed. Parameters = {observation["param"]}"""
)
by_name[name][attribute].append(observation["attribute"][attribute])
for name in by_name:
for attribute in attributes_by_name[name]:
by_name[name][attribute] = np.array(by_name[name][attribute])
return by_name, parameter_names
def by_name_to_by_param(by_name: dict):
"""
Convert aggregation by name to aggregation by name and parameter values.
"""
by_param = dict()
for name in by_name.keys():
for i, parameters in enumerate(by_name[name]["param"]):
param_key = (name, tuple(parameters))
if param_key not in by_param:
by_param[param_key] = dict()
for key in by_name[name].keys():
by_param[param_key][key] = list()
by_param[param_key]["attributes"] = by_name[name]["attributes"]
# special case for PTA models
if "isa" in by_name[name]:
by_param[param_key]["isa"] = by_name[name]["isa"]
for attribute in by_name[name]["attributes"]:
by_param[param_key][attribute].append(by_name[name][attribute][i])
if "supports" in by_name[name]:
for support in by_name[name]["supports"]:
by_param[param_key][support].append(by_name[name][support][i])
# Required for match_parameter_valuse in _try_fits
by_param[param_key]["param"].append(by_name[name]["param"][i])
return by_param
def by_param_to_by_name(by_param: dict) -> dict:
"""
Convert aggregation by name and parameter values to aggregation by name only.
"""
by_name = dict()
for param_key in by_param.keys():
name, _ = param_key
if name not in by_name:
by_name[name] = dict()
for key in by_param[param_key].keys():
by_name[name][key] = list()
by_name[name]["attributes"] = by_param[param_key]["attributes"]
# special case for PTA models
if "isa" in by_param[param_key]:
by_name[name]["isa"] = by_param[param_key]["isa"]
for attribute in by_name[name]["attributes"]:
by_name[name][attribute].extend(by_param[param_key][attribute])
if "supports" in by_param[param_key]:
for support in by_param[param_key]["supports"]:
by_name[name][support].extend(by_param[param_key][support])
by_name[name]["param"].extend(by_param[param_key]["param"])
for name in by_name.keys():
for attribute in by_name[name]["attributes"]:
by_name[name][attribute] = np.array(by_name[name][attribute])
return by_name
def normalize_nfp_in_aggregate(aggregate, nfp_norm):
for name in aggregate.keys():
for new_name, old_name, norm_function in nfp_norm:
if old_name in aggregate[name]["attributes"]:
aggregate[name][new_name] = norm_function(aggregate[name].pop(old_name))
aggregate[name]["attributes"].remove(old_name)
aggregate[name]["attributes"].append(new_name)
def shift_param_in_aggregate(aggregate, parameters, parameter_shift):
"""
Remove entries which do not have certain parameter values from `aggregate`.
:param aggregate: aggregated measurement data, must be a dict conforming to
aggregate[state or transition name]['param'] = (first parameter value, second parameter value, ...)
and
aggregate[state or transition name]['attributes'] = [list of keys with measurement data, e.g. 'power' or 'duration']
:param parameters: list of parameters, used to map parameter index to parameter name. parameters=['foo', ...] means 'foo' is the first parameter
:param parameter_shift: [[name, function], [name, function], ...] list of parameter values to alter.
"""
for param_name, param_shift_function in parameter_shift:
if param_name == "*":
for name in aggregate.keys():
for param_list in aggregate[name]["param"]:
for param_index in range(len(param_list)):
param_list[param_index] = param_shift_function(
param_list[param_index]
)
else:
param_index = parameters.index(param_name)
for name in aggregate.keys():
for param_list in aggregate[name]["param"]:
if param_list[param_index] is not None:
param_list[param_index] = param_shift_function(
param_list[param_index]
)
def filter_aggregate_by_param(aggregate, parameters, parameter_filter):
"""
Remove entries which do not have certain parameter values from `aggregate`.
:param aggregate: aggregated measurement data, must be a dict conforming to
aggregate[state or transition name]['param'] = (first parameter value, second parameter value, ...)
and
aggregate[state or transition name]['attributes'] = [list of keys with measurement data, e.g. 'power' or 'duration']
:param parameters: list of parameters, used to map parameter index to parameter name. parameters=['foo', ...] means 'foo' is the first parameter
:param parameter_filter: [[name, value], [name, value], ...] list of parameter values to keep, all others are removed. Values refer to normalizad parameter data.
"""
for param_name_and_value in parameter_filter:
param_index = parameters.index(param_name_and_value[0])
param_value = soft_cast_int(param_name_and_value[1])
names_to_remove = set()
for name in aggregate.keys():
indices_to_keep = list(
map(lambda x: x[param_index] == param_value, aggregate[name]["param"])
)
aggregate[name]["param"] = list(
map(
lambda iv: iv[1],
filter(
lambda iv: indices_to_keep[iv[0]],
enumerate(aggregate[name]["param"]),
),
)
)
if len(indices_to_keep) == 0:
logger.debug("??? {}->{}".format(parameter_filter, name))
names_to_remove.add(name)
else:
for attribute in aggregate[name]["attributes"]:
aggregate[name][attribute] = aggregate[name][attribute][
indices_to_keep
]
if len(aggregate[name][attribute]) == 0:
names_to_remove.add(name)
for name in names_to_remove:
aggregate.pop(name)
def detect_outliers_in_aggregate(aggregate, z_limit=10, remove_outliers=False):
for name in aggregate.keys():
indices_to_remove = set()
attributes = list()
for attribute in aggregate[name]["attributes"]:
data = aggregate[name][attribute]
z_scores = (data - np.mean(data)) / np.std(data)
outliers = np.abs(z_scores) > z_limit
if np.any(outliers) and remove_outliers:
indices_to_remove = indices_to_remove.union(
np.arange(len(outliers))[outliers]
)
attributes.append(attribute)
elif np.any(outliers):
logger.info(
f"{name} {attribute} has {len(z_scores[outliers])} outliers"
)
if indices_to_remove:
# Assumption: len(aggregate[name][attribute]) is the same for each
# attribute.
logger.info(
f"Removing outliers {indices_to_remove} from {name}. Affected attributes: {attributes}"
)
indices_to_keep = map(
lambda x: x not in indices_to_remove, np.arange(len(outliers))
)
indices_to_keep = np.array(list(indices_to_keep))
for attribute in aggregate[name]["attributes"]:
aggregate[name][attribute] = aggregate[name][attribute][indices_to_keep]
aggregate[name]["param"] = list(
map(
lambda iv: iv[1],
filter(
lambda iv: indices_to_keep[iv[0]],
enumerate(aggregate[name]["param"]),
),
)
)
def aggregate_measures(aggregate: float, actual: list) -> dict:
"""
Calculate error measures for model value on data list.
arguments:
aggregate -- model value (float or int)
actual -- real-world / reference values (list of float or int)
return value:
See regression_measures
"""
aggregate_array = np.array([aggregate] * len(actual))
return regression_measures(aggregate_array, np.array(actual))
def regression_measures(predicted: np.ndarray, actual: np.ndarray):
"""
Calculate error measures by comparing model values to reference values.
arguments:
predicted -- model values (np.ndarray)
actual -- real-world / reference values (np.ndarray)
Returns a dict containing the following measures:
mae -- Mean Absolute Error
mape -- Mean Absolute Percentage Error,
if all items in actual are non-zero (NaN otherwise)
smape -- Symmetric Mean Absolute Percentage Error,
if no 0,0-pairs are present in actual and predicted (NaN otherwise)
msd -- Mean Square Deviation
rmsd -- Root Mean Square Deviation
ssr -- Sum of Squared Residuals
rsq -- R^2 measure, see sklearn.metrics.r2_score
count -- Number of values
"""
if type(predicted) != np.ndarray:
raise ValueError("first arg must be ndarray, is {}".format(type(predicted)))
if type(actual) != np.ndarray:
raise ValueError("second arg must be ndarray, is {}".format(type(actual)))
deviations = predicted - actual
# mean = np.mean(actual)
if len(deviations) == 0:
return {}
measures = {
"mae": np.mean(np.abs(deviations), dtype=np.float64),
"msd": np.mean(deviations**2, dtype=np.float64),
"rmsd": np.sqrt(np.mean(deviations**2), dtype=np.float64),
"ssr": np.sum(deviations**2, dtype=np.float64),
"rsq": r2_score(actual, predicted),
"count": len(actual),
}
# rsq_quotient = np.sum((actual - mean)**2, dtype=np.float64) * np.sum((predicted - mean)**2, dtype=np.float64)
if np.all(actual != 0):
measures["mape"] = np.mean(np.abs(deviations / actual)) * 100 # bad measure
else:
measures["mape"] = np.nan
if np.all(np.abs(predicted) + np.abs(actual) != 0):
measures["smape"] = (
np.mean(np.abs(deviations) / ((np.abs(predicted) + np.abs(actual)) / 2))
* 100
)
else:
measures["smape"] = np.nan
# if np.all(rsq_quotient != 0):
# measures['rsq'] = (np.sum((actual - mean) * (predicted - mean), dtype=np.float64)**2) / rsq_quotient
return measures
class OptionalTimingAnalysis:
def __init__(self, enabled=True):
self.enabled = enabled
self.wrapped_lines = list()
self.index = 1
def get_header(self):
ret = ""
if self.enabled:
ret += "#define TIMEIT(index, functioncall) "
ret += "counter.start(); "
ret += "functioncall; "
ret += "counter.stop();"
ret += 'kout << endl << index << " :: " << counter.value << "/" << counter.overflow << endl;\n'
return ret
def wrap_codeblock(self, codeblock):
if not self.enabled:
return codeblock
lines = codeblock.split("\n")
ret = list()
for line in lines:
if re.fullmatch(".+;", line):
ret.append("TIMEIT( {:d}, {} )".format(self.index, line))
self.wrapped_lines.append(line)
self.index += 1
else:
ret.append(line)
return "\n".join(ret)
|