|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# for d3 layouts: |
| 4 | +# 1) Tree |
| 5 | +# 2) Treemap |
| 6 | +# 3) Pack |
| 7 | +# 4) Partition |
| 8 | +# 5) Cluster |
| 9 | +# 6) Heirarchy |
| 10 | + |
| 11 | +import json |
| 12 | + |
| 13 | +import utils |
| 14 | + |
| 15 | + |
| 16 | +def raise_convert_error(obj): |
| 17 | + raise utils.ConvertException(obj, 'heirarchy') |
| 18 | + |
| 19 | + |
| 20 | +def convert(obj): |
| 21 | + """ |
| 22 | + Try to convert an object to a json heirarchy object like (from d3): |
| 23 | + { |
| 24 | + "name": "flare", |
| 25 | + "children": [ |
| 26 | + { |
| 27 | + "name": "analytics", |
| 28 | + "children": [ |
| 29 | + {"name": "AgglomerativeCluster", "size": 3938}, |
| 30 | + {"name": "CommunityStructure", "size": 3812}, |
| 31 | + {"name": "MergeEdge", "size": 743} |
| 32 | + ] |
| 33 | + }, |
| 34 | + { |
| 35 | + "name": "graph", |
| 36 | + "children": [ |
| 37 | + {"name": "BetweennessCentrality", "size": 3534}, |
| 38 | + {"name": "LinkDistance", "size": 5731} |
| 39 | + ] |
| 40 | + } |
| 41 | + ] |
| 42 | + } |
| 43 | + """ |
| 44 | + return { |
| 45 | + dict: from_dict, |
| 46 | + list: from_list, |
| 47 | + }.get(type(obj), raise_convert_error)(obj) |
| 48 | + |
| 49 | + |
| 50 | +def from_dict(d): |
| 51 | + """ |
| 52 | + format: |
| 53 | + {'main name': {children....}} |
| 54 | +
|
| 55 | + where children are of type: |
| 56 | + {'name': <value or children>} |
| 57 | + """ |
| 58 | + children = from_dict_to_children(d) |
| 59 | + if len(children) == 1: |
| 60 | + return json.dumps(children[0]) |
| 61 | + else: |
| 62 | + # TODO make this a more informative error |
| 63 | + raise Exception("Invalid conversion") |
| 64 | + |
| 65 | + |
| 66 | +def from_dict_to_children(d): |
| 67 | + children = [] |
| 68 | + for k, v in d.iteritems(): |
| 69 | + if type(v) == dict: |
| 70 | + children.append({'name': k, \ |
| 71 | + 'children': from_dict_to_children(v)}) |
| 72 | + else: |
| 73 | + children.append({'name': k, 'size': v}) |
| 74 | + return children |
| 75 | + |
| 76 | + |
| 77 | +def from_list(l): |
| 78 | + """ |
| 79 | + format: |
| 80 | + [ [1, [2,3,4], 5] ] |
| 81 | +
|
| 82 | + should be a list of lists with the dimension 0 len 1 |
| 83 | + so that the main_name can be set correctly |
| 84 | + """ |
| 85 | + if len(l) != 1: |
| 86 | + return from_dict(list_to_dict([l])) |
| 87 | + else: |
| 88 | + return from_dict(list_to_dict(l)) |
| 89 | + |
| 90 | + |
| 91 | +def list_to_dict(l, level=''): |
| 92 | + """ |
| 93 | + Use a numbered heirarchy |
| 94 | + 1, 1.1, 1.2, 1.2.1 |
| 95 | + """ |
| 96 | + d = {} |
| 97 | + for (i, v) in enumerate(l): |
| 98 | + nl = '%s%i' % (level, i) |
| 99 | + if type(v) == list: |
| 100 | + d[nl] = list_to_dict(v, nl + '.') |
| 101 | + else: |
| 102 | + d[nl] = v |
| 103 | + return d |
0 commit comments