Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""Assorted helper methods"""
2from collections.abc import Iterable
3import numpy as np
6def initsolwarning(result, category="uncategorized"):
7 "Creates a results dictionary for a particular category of warning."
8 if "warnings" not in result:
9 result["warnings"] = {}
10 if category not in result["warnings"]:
11 result["warnings"][category] = []
14def appendsolwarning(msg, data, result, category="uncategorized"):
15 "Append a particular category of warnings to a solution."
16 result["warnings"][category].append((msg, data))
19@np.vectorize
20def isnan(element):
21 "Determine if something of arbitrary type is a numpy nan."
22 try:
23 return np.isnan(element)
24 except TypeError:
25 return False
28def maybe_flatten(value):
29 "Extract values from 0-d numpy arrays, if necessary"
30 if hasattr(value, "shape") and not value.shape:
31 return value.flatten()[0] # 0-d numpy arrays
32 return value
35def try_str_without(item, excluded, *, latex=False):
36 "Try to call item.str_without(excluded); fall back to str(item)"
37 if latex and hasattr(item, "latex"):
38 return item.latex(excluded)
39 if hasattr(item, "str_without"):
40 return item.str_without(excluded)
41 return str(item)
44def mag(c):
45 "Return magnitude of a Number or Quantity"
46 return getattr(c, "magnitude", c)
49def is_sweepvar(sub):
50 "Determines if a given substitution indicates a sweep."
51 return splitsweep(sub)[0]
54def splitsweep(sub):
55 "Splits a substitution into (is_sweepvar, sweepval)"
56 try:
57 sweep, value = sub
58 if sweep is "sweep" and (isinstance(value, Iterable) or # pylint: disable=literal-comparison
59 hasattr(value, "__call__")):
60 return True, value
61 except (TypeError, ValueError):
62 pass
63 return False, None