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

1from __future__ import print_function 

2from builtins import map 

3from builtins import str 

4from builtins import range 

5import sys 

6import numpy as np 

7 

8__all__ = ['nameSanitize', 'printDict', 'printSimpleDict'] 

9 

10 

11def nameSanitize(inString): 

12 """ 

13 Convert a string to a more file name (and web) friendly format. 

14 

15 Parameters 

16 ---------- 

17 inString : str 

18 The input string to be sanitized. Typically these are combinations of metric names and metadata. 

19 

20 Returns 

21 ------- 

22 str 

23 The string after removal/replacement of non-filename friendly characters. 

24 """ 

25 # Replace <, > and = signs. 

26 outString = inString.replace('>', 'gt').replace('<', 'lt').replace('=', 'eq') 

27 # Remove single-spaces, strip '.'s and ','s 

28 outString = outString.replace(' ', '_').replace('.', '_').replace(',', '') 

29 # and remove / and \ 

30 outString = outString.replace('/', '_').replace('\\', '_') 

31 # and remove parentheses 

32 outString = outString.replace('(', '').replace(')', '') 

33 # Remove ':' and ';" 

34 outString = outString.replace(':', '_').replace(';', '_') 

35 # Replace '%' and # 

36 outString = outString.replace('%', '_').replace('#', '_') 

37 # Remove '__' 

38 while '__' in outString: 

39 outString = outString.replace('__', '_') 

40 return outString 

41 

42 

43def _myformat(args, delimiter=' '): 

44 # Generic line formatter to let you specify delimiter between text fields. 

45 writestring = '' 

46 # Wrap in a list if something like an int gets passed in 

47 if not hasattr(args, '__iter__'): 

48 args = [args] 

49 for a in args: 

50 if isinstance(a, list): 

51 if len(a) > 1: 

52 ap = ','.join(map(str, a)) 

53 else: 

54 ap = ''.join(map(str, a)) 

55 writestring += '%s%s' % (ap, delimiter) 

56 else: 

57 writestring += '%s%s' % (a, delimiter) 

58 return writestring 

59 

60 

61def _myformatdict(adict, delimiter=' '): 

62 # Generic line formatter used for dictionaries. 

63 writestring = '' 

64 for k, v in adict.items(): 

65 if isinstance(v, list): 

66 if len(v) > 1: 

67 vp = ','.join(map(str, v)) 

68 else: 

69 vp = ''.join(map(str, v)) 

70 writestring += '%s:%s%s' % (k, vp, delimiter) 

71 else: 

72 writestring += '%s:%s%s' % (k, v, delimiter) 

73 return writestring 

74 

75 

76def printDict(content, label, filehandle=None, delimiter=' ', _level=0): 

77 """ 

78 Print dictionaries (and/or nested dictionaries) nicely. 

79 Can also print other simpler items (such as numpy ndarray) nicely too. 

80 This is used to print the config files. 

81 

82 Parameters 

83 ---------- 

84 content : dict 

85 The content to pretty print. 

86 label : str 

87 A header for this level of the dictionary. 

88 filename : file 

89 Output destination. If None, prints to stdout. 

90 delimiter : str 

91 User specified delimiter between fields. 

92 _level : int 

93 Internal use (controls level of indent). 

94 """ 

95 # Get set up with basic file output information. 

96 if filehandle is None: 

97 filehandle = sys.stdout 

98 # And set character to use to indent sets of parameters related to a single dictionary. 

99 baseindent = '%s' % (delimiter) 

100 indent = '' 

101 for i in range(_level-1): 

102 indent += '%s' % (baseindent) 

103 # Print data (this is also the termination of the recursion if given nested dictionaries). 

104 if not isinstance(content, dict): 

105 if isinstance(content, str) or isinstance(content, float) or isinstance(content, int): 

106 print('%s%s%s%s' % (indent, label, delimiter, str(content)), file=filehandle) 

107 else: 

108 if isinstance(content, np.ndarray): 

109 if content.dtype.names is not None: 

110 print('%s%s%s' % (indent, delimiter, label), file=filehandle) 

111 for element in content: 

112 print('%s%s%s%s%s' % (indent, delimiter, indent, delimiter, _myformat(element)), file=filehandle) 

113 else: 

114 print('%s%s%s%s' % (indent, label, delimiter, _myformat(content)), file=filehandle) 

115 else: 

116 print('%s%s%s%s' % (indent, label, delimiter, _myformat(content)), file=filehandle) 

117 return 

118 # Allow user to specify print order of (some or all) items in order via 'keyorder'. 

119 # 'keyorder' is list stored in the dictionary. 

120 if 'keyorder' in content: 

121 orderkeys = content['keyorder'] 

122 # Check keys in 'keyorder' are actually present in dictionary : remove those which aren't. 

123 missingkeys = set(orderkeys).difference(set(content.keys())) 

124 for m in missingkeys: 

125 orderkeys.remove(m) 

126 otherkeys = sorted(list(set(content.keys()).difference(set(orderkeys)))) 

127 keys = orderkeys + otherkeys 

128 keys.remove('keyorder') 

129 else: 

130 keys = sorted(content.keys()) 

131 # Print data from dictionary. 

132 print('%s%s%s:' % (indent, delimiter, label), file=filehandle) 

133 _level += 2 

134 for k in keys: 

135 printDict(content[k], k, filehandle, delimiter, _level) 

136 _level -= 2 

137 

138 

139def printSimpleDict(topdict, subkeyorder, filehandle=None, delimiter=' '): 

140 """ 

141 Print a simple one-level nested dictionary nicely across the screen, 

142 with one line per top-level key and all sub-level keys aligned. 

143 

144 Parameters 

145 ---------- 

146 topdict : dict 

147 The dictionary to pretty print 

148 subkeyorder : list of strings 

149 The order to print the values of the dictionary. 

150 filehandle : file 

151 File output object, if None then uses stdout. 

152 delimiter : str 

153 User specified delimiter between fields. 

154 """ 

155 # Get set up with basic file output information. 

156 if filehandle is None: 

157 filehandle = sys.stdout 

158 # Get all sub-level keys. 

159 subkeys = [] 

160 for key in topdict: 

161 subkeys += list(topdict[key].keys()) 

162 subkeys = list(set(subkeys)) 

163 # Align subkeys with 'subkeyorder' and then alphabetize any remaining. 

164 missingkeys = set(subkeyorder).difference(set(subkeys)) 

165 for m in missingkeys: 

166 subkeyorder.remove(m) 

167 otherkeys = sorted(list(set(subkeys).difference(set(subkeyorder)))) 

168 subkeys = subkeyorder + otherkeys 

169 # Print header. 

170 writestring = '#' 

171 for s in subkeys: 

172 writestring += '%s%s' % (s, delimiter) 

173 print(writestring, file=filehandle) 

174 # Now go through and print. 

175 for k in topdict: 

176 writestring = '' 

177 for s in subkeys: 

178 if s in topdict[k]: 

179 if isinstance(topdict[k][s], str) or isinstance(topdict[k][s], float) or isinstance(topdict[k][s], int): 

180 writestring += '%s%s' % (topdict[k][s], delimiter) 

181 elif isinstance(topdict[k][s], dict): 

182 writestring += '%s%s' % (_myformatdict(topdict[k][s], delimiter=delimiter), delimiter) 

183 else: 

184 writestring += '%s%s' % (_myformat(topdict[k][s]), delimiter) 

185 else: 

186 writestring += '%s' % (delimiter) 

187 print(writestring, file=filehandle)