Coverage for gpkit/small_scripts.py: 100%
43 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-07 22:13 -0500
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-07 22:13 -0500
1"""Assorted helper methods"""
2from collections.abc import Iterable
3import numpy as np
6def broadcast_substitution(key, array):
7 "Broadcasts input into the shape of a given key"
8 return np.broadcast_to(array, reversed(key.key.shape)).T
11def veclinkedfn(linkedfn, i):
12 "Generate an indexed linking function."
13 def newlinkedfn(c):
14 "Linked function that pulls out a particular index"
15 return np.array(linkedfn(c))[i]
16 return newlinkedfn
19def initsolwarning(result, category="uncategorized"):
20 "Creates a results dictionary for a particular category of warning."
21 if "warnings" not in result:
22 result["warnings"] = {}
23 if category not in result["warnings"]:
24 result["warnings"][category] = []
27def appendsolwarning(msg, data, result, category="uncategorized"):
28 "Append a particular category of warnings to a solution."
29 result["warnings"][category].append((msg, data))
32@np.vectorize
33def isnan(element):
34 "Determine if something of arbitrary type is a numpy nan."
35 try:
36 return np.isnan(element)
37 except TypeError:
38 return False
41def maybe_flatten(value):
42 "Extract values from 0-d numpy arrays, if necessary"
43 if hasattr(value, "size") and value.size == 1:
44 return value.item()
45 return value
48def try_str_without(item, excluded, *, latex=False):
49 "Try to call item.str_without(excluded); fall back to str(item)"
50 if latex and hasattr(item, "latex"):
51 return item.latex(excluded)
52 if hasattr(item, "str_without"):
53 return item.str_without(excluded)
54 return str(item)
57def mag(c):
58 "Return magnitude of a Number or Quantity"
59 return getattr(c, "magnitude", c)
62def is_sweepvar(sub):
63 "Determines if a given substitution indicates a sweep."
64 return splitsweep(sub)[0]
67def splitsweep(sub):
68 "Splits a substitution into (is_sweepvar, sweepval)"
69 try:
70 sweep, value = sub
71 if sweep is "sweep" and (isinstance(value, Iterable) or # pylint: disable=literal-comparison
72 hasattr(value, "__call__")):
73 return True, value
74 except (TypeError, ValueError):
75 pass
76 return False, None