Hide keyboard shortcuts

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 

4 

5 

6def appendsolwarning(msg, data, result, category="uncategorized"): 

7 "Append a particular category of warnings to a solution." 

8 if "warnings" not in result: 

9 result["warnings"] = {} 

10 if category not in result["warnings"]: 

11 result["warnings"][category] = [] 

12 result["warnings"][category].append((msg, data)) 

13 

14 

15@np.vectorize 

16def isnan(element): 

17 "Determine if something of arbitrary type is a numpy nan." 

18 try: 

19 return np.isnan(element) 

20 except TypeError: 

21 return False 

22 

23 

24def maybe_flatten(value): 

25 "Extract values from 0-d numpy arrays, if necessary" 

26 if hasattr(value, "shape") and not value.shape: 

27 return value.flatten()[0] # 0-d numpy arrays 

28 return value 

29 

30 

31def try_str_without(item, excluded, *, latex=False): 

32 "Try to call item.str_without(excluded); fall back to str(item)" 

33 if latex and hasattr(item, "latex"): 

34 return item.latex(excluded) 

35 if hasattr(item, "str_without"): 

36 return item.str_without(excluded) 

37 return str(item) 

38 

39 

40def mag(c): 

41 "Return magnitude of a Number or Quantity" 

42 return getattr(c, "magnitude", c) 

43 

44 

45def is_sweepvar(sub): 

46 "Determines if a given substitution indicates a sweep." 

47 return splitsweep(sub)[0] 

48 

49 

50def splitsweep(sub): 

51 "Splits a substitution into (is_sweepvar, sweepval)" 

52 try: 

53 sweep, value = sub 

54 if sweep is "sweep" and (isinstance(value, Iterable) or # pylint: disable=literal-comparison 

55 hasattr(value, "__call__")): 

56 return True, value 

57 except (TypeError, ValueError): 

58 pass 

59 return False, None