-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjsonsummary.py
245 lines (224 loc) · 6.08 KB
/
jsonsummary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import exceptions
import os
import openpyxl
class EnhancementWorkbookError (exceptions.Exception):
pass
class EnhancementWorkbook (object):
def __init__ (self, workbookFilename, mode="readonly"):
self.workbookFilename = workbookFilename
self.mode = mode
if mode == "new":
if os.path.exists (workbookFilename):
raise EnhancementWorkbookError,\
"Can't open workbook: '%s' already exists" %\
workbookFilename
self.wb = openpyxl.Workbook ()
else:
self.wb = openpyxl.load_workbook (workbookFilename)
def save (self):
if self.mode == "readonly":
raise EnhancementWorkbookError,\
"Can't save read-only workbook: '%s'" %\
self.workbookFilename
elif self.mode == "new":
if os.path.exists (self.workbookFilename):
raise EnhancementWorkbookError,\
"Can't save new workbook: '%s' already exists" %\
self.workbookFilename
self.wb.save (self.workbookFilename)
if __name__ == "__main__":
import getopt
import json
import sys
import traceback
optlist, args = getopt.getopt (sys.argv[1:], '')
for (option, value) in optlist:
pass
if len (args) < 1:
print "--Usage: <inputFile> [<outputFile>]"
sys.exit (0)
(root, jsonExt) = os.path.splitext (args [0])
if not jsonExt: jsonExt = ".json"
# Get JSON information
try:
jsonFile = open (root + jsonExt)
jsonData = json.loads (jsonFile.read ())
jsonFile.close ()
except exceptions.Exception, e:
print "--Can't load JSON file (%s)" % e
traceback.print_exc ()
sys.exit (0)
totalCount = jsonData ["total_count"]
# Open workbook
if len (args) > 1:
workbookFilename = args [1]
workRoot, workExt = os.path.splitext (args [1])
if not workExt: workExt = ".xlsx"
else:
workRoot = root
workExt = ".xlsx"
try:
ewb = EnhancementWorkbook (workRoot + workExt, "new")
except exceptions.Exception, e:
print "--Error: %s" % e
sys.exit (0)
wb = ewb.wb
distributions = wb.active
distributions.title = "Input Distributions"
wb.create_sheet (0, title="Input Lists")
lists = wb.active
wb.create_sheet (0, title="Input Map")
map = wb.active
map.append ((
'Name',
'Type',
'List',
'Frequency',
'Present',
'Missing',
'Values',
'Title'))
variableSequence = jsonData ["variable_sequence"]
for variableName in variableSequence:
variable = jsonData ["variables"] [variableName]
distribution = variable ["distribution"]
map.append ((
variable ["name"],
variable ["json_type"],
variable.get ("code_list_name"),
distribution ["frequency_type"],
distribution ["non_missing_frequency"],
distribution ["missing_frequency"],
distribution ["unique_values"],
variable.get ("title")
))
lists.append (("Name", "Code", "Label"))
codeLists = jsonData.get ("code_lists")
if codeLists:
for codeListName in sorted (codeLists.keys ()):
codeList = codeLists [codeListName]
sequence = codeList ["sequence"]
table = codeList ["table"]
allInteger = True
for code in sequence:
if not code.isdigit ():
allInteger = False
break
for code in sequence:
if allInteger:
outputCode = int (code)
else:
outputCode = code
lists.append ((codeListName, outputCode, table [code]))
distributions.append (("Name", "Frequency", "Measure", "Value", "Label"))
distributions.append (("", totalCount, "All records"))
variableSequence = jsonData ["variable_sequence"]
emptyList = {}
for variableName in variableSequence:
listName = variable.get ("code_list_name")
if listName:
listObject = jsonData ["code_lists"].get (listName)
listTable = listObject ["table"]
else:
listTable = emptyList
variable = jsonData ["variables"] [variableName]
jsonType = variable ["json_type"]
distribution = variable ["distribution"]
distributions.append ((
variableName,
"",
"Title",
variable.get ("title")
))
distributions.append ((
variableName,
distribution ["non_missing_frequency"],
"Records"
))
uniqueValue = None
if distribution ["frequency_type"] == "constant":
uniqueValue = distribution ["min_value"]
distributions.append ((
variableName,
distribution ["frequency_type"],
"Distribution",
uniqueValue
))
if distribution ["frequency_type"] == "empty":
continue
if distribution ["missing_frequency"] != 0:
distributions.append ((
variableName,
distribution ["missing_frequency"],
"Missing"
))
if distribution ["frequency_type"] not in ("constant", "id", "unique"):
distributions.append ((
variableName,
distribution ["unique_values"],
"Unique values"
))
if distribution ["unique_frequency"]:
distributions.append ((
variableName,
distribution ["unique_frequency"],
"Unique frequency"
))
distributions.append ((
variableName,
distribution ["modal_frequency"],
"Mode",
distribution ["modal_value"],
listTable.get (distribution ["modal_value"])
))
if distribution ["frequency_type"] != "constant":
distributions.append ((
variableName,
None,
"Minimum",
distribution ["min_value"],
listTable.get (distribution ["min_value"])
))
distributions.append ((
variableName,
None,
"Maximum",
distribution ["max_value"],
listTable.get (distribution ["max_value"])
))
if distribution ["frequency_type"] == "variable":
distributionTable = distribution ["distribution"]
keys = distributionTable.keys ()
if jsonType == "decimal":
keys.sort (lambda x, y: cmp (float (x), float (y)))
elif jsonType == "integer":
keys.sort (lambda x, y: cmp (int (x), int (y)))
else:
keys.sort ()
listedCount = 0
for key in keys:
count = distributionTable [key]
if jsonType == "decimal":
keyValue = float (key)
elif jsonType == "integer":
keyValue = int (key)
else:
keyValue = key
if count > 1:
distributions.append ((
variableName,
count,
None,
keyValue,
listTable.get (key)
))
listedCount += count
otherCount = distribution ["non_missing_frequency"] - listedCount
if otherCount:
distributions.append ((
variableName,
otherCount,
"Others"
))
# Save workbook
ewb.save ()