Coverage for python/lsst/sims/maf/utils/outputUtils.py : 8%

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
8__all__ = ['nameSanitize', 'printDict', 'printSimpleDict']
11def nameSanitize(inString):
12 """
13 Convert a string to a more file name friendly format.
15 Parameters
16 ----------
17 inString : str
18 The input string to be sanitized. Typically these are combinations of metric names and metadata.
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 # Remove '__'
36 while '__' in outString:
37 outString = outString.replace('__', '_')
38 return outString
41def _myformat(args, delimiter=' '):
42 # Generic line formatter to let you specify delimiter between text fields.
43 writestring = ''
44 # Wrap in a list if something like an int gets passed in
45 if not hasattr(args, '__iter__'):
46 args = [args]
47 for a in args:
48 if isinstance(a, list):
49 if len(a) > 1:
50 ap = ','.join(map(str, a))
51 else:
52 ap = ''.join(map(str, a))
53 writestring += '%s%s' % (ap, delimiter)
54 else:
55 writestring += '%s%s' % (a, delimiter)
56 return writestring
59def _myformatdict(adict, delimiter=' '):
60 # Generic line formatter used for dictionaries.
61 writestring = ''
62 for k, v in adict.items():
63 if isinstance(v, list):
64 if len(v) > 1:
65 vp = ','.join(map(str, v))
66 else:
67 vp = ''.join(map(str, v))
68 writestring += '%s:%s%s' % (k, vp, delimiter)
69 else:
70 writestring += '%s:%s%s' % (k, v, delimiter)
71 return writestring
74def printDict(content, label, filehandle=None, delimiter=' ', _level=0):
75 """
76 Print dictionaries (and/or nested dictionaries) nicely.
77 Can also print other simpler items (such as numpy ndarray) nicely too.
78 This is used to print the config files.
80 Parameters
81 ----------
82 content : dict
83 The content to pretty print.
84 label : str
85 A header for this level of the dictionary.
86 filename : file
87 Output destination. If None, prints to stdout.
88 delimiter : str
89 User specified delimiter between fields.
90 _level : int
91 Internal use (controls level of indent).
92 """
93 # Get set up with basic file output information.
94 if filehandle is None:
95 filehandle = sys.stdout
96 # And set character to use to indent sets of parameters related to a single dictionary.
97 baseindent = '%s' % (delimiter)
98 indent = ''
99 for i in range(_level-1):
100 indent += '%s' % (baseindent)
101 # Print data (this is also the termination of the recursion if given nested dictionaries).
102 if not isinstance(content, dict):
103 if isinstance(content, str) or isinstance(content, float) or isinstance(content, int):
104 print('%s%s%s%s' % (indent, label, delimiter, str(content)), file=filehandle)
105 else:
106 if isinstance(content, np.ndarray):
107 if content.dtype.names is not None:
108 print('%s%s%s' % (indent, delimiter, label), file=filehandle)
109 for element in content:
110 print('%s%s%s%s%s' % (indent, delimiter, indent, delimiter, _myformat(element)), file=filehandle)
111 else:
112 print('%s%s%s%s' % (indent, label, delimiter, _myformat(content)), file=filehandle)
113 else:
114 print('%s%s%s%s' % (indent, label, delimiter, _myformat(content)), file=filehandle)
115 return
116 # Allow user to specify print order of (some or all) items in order via 'keyorder'.
117 # 'keyorder' is list stored in the dictionary.
118 if 'keyorder' in content:
119 orderkeys = content['keyorder']
120 # Check keys in 'keyorder' are actually present in dictionary : remove those which aren't.
121 missingkeys = set(orderkeys).difference(set(content.keys()))
122 for m in missingkeys:
123 orderkeys.remove(m)
124 otherkeys = sorted(list(set(content.keys()).difference(set(orderkeys))))
125 keys = orderkeys + otherkeys
126 keys.remove('keyorder')
127 else:
128 keys = sorted(content.keys())
129 # Print data from dictionary.
130 print('%s%s%s:' % (indent, delimiter, label), file=filehandle)
131 _level += 2
132 for k in keys:
133 printDict(content[k], k, filehandle, delimiter, _level)
134 _level -= 2
137def printSimpleDict(topdict, subkeyorder, filehandle=None, delimiter=' '):
138 """
139 Print a simple one-level nested dictionary nicely across the screen,
140 with one line per top-level key and all sub-level keys aligned.
142 Parameters
143 ----------
144 topdict : dict
145 The dictionary to pretty print
146 subkeyorder : list of strings
147 The order to print the values of the dictionary.
148 filehandle : file
149 File output object, if None then uses stdout.
150 delimiter : str
151 User specified delimiter between fields.
152 """
153 # Get set up with basic file output information.
154 if filehandle is None:
155 filehandle = sys.stdout
156 # Get all sub-level keys.
157 subkeys = []
158 for key in topdict:
159 subkeys += list(topdict[key].keys())
160 subkeys = list(set(subkeys))
161 # Align subkeys with 'subkeyorder' and then alphabetize any remaining.
162 missingkeys = set(subkeyorder).difference(set(subkeys))
163 for m in missingkeys:
164 subkeyorder.remove(m)
165 otherkeys = sorted(list(set(subkeys).difference(set(subkeyorder))))
166 subkeys = subkeyorder + otherkeys
167 # Print header.
168 writestring = '#'
169 for s in subkeys:
170 writestring += '%s%s' % (s, delimiter)
171 print(writestring, file=filehandle)
172 # Now go through and print.
173 for k in topdict:
174 writestring = ''
175 for s in subkeys:
176 if s in topdict[k]:
177 if isinstance(topdict[k][s], str) or isinstance(topdict[k][s], float) or isinstance(topdict[k][s], int):
178 writestring += '%s%s' % (topdict[k][s], delimiter)
179 elif isinstance(topdict[k][s], dict):
180 writestring += '%s%s' % (_myformatdict(topdict[k][s], delimiter=delimiter), delimiter)
181 else:
182 writestring += '%s%s' % (_myformat(topdict[k][s]), delimiter)
183 else:
184 writestring += '%s' % (delimiter)
185 print(writestring, file=filehandle)