Map the dictionary into factorgraph-viz format. See https://github.com/mbforbes/factorgraph-viz

        :param d: The dictionary
        :return: The formatted dictionary
190043
def factorgraph_viz(d):
        
        m = defaultdict(list)

        for node in d['nodes']:
            m['nodes'].append(dict(
                id=node['id'],
                type='rv'
            ))

        for factor in d['factors']:
            m['nodes'].append(dict(
                id=factor['id'],
                type='fac'
            ))

            for source in factor['sources']:
                m['links'].append(dict(
                    source=source,
                    target=factor['id']
                ))
            if factor['sink']:
                m['links'].append(dict(
                    source=factor['id'],
                    target=factor['sink']
                ))

        return dict(m)
949549
def translate_obj(self,d,fname):
        
        if fname not in d:
            # TODO: consider adding arg for failure on null
            return None

        lf = M.label_field(fname)
        id = d[fname]
        id = self.make_canonical_identifier(id)
        #if id.startswith('MGI:MGI:'):
        #    id = id.replace('MGI:MGI:','MGI:')
        obj = {'id': id}

        if id:
            if self._use_amigo_schema(self.object_category):
                iri = expand_uri(id)
            else:
                iri = expand_uri(id, [get_curie_map('{}/cypher/curies'.format(self.config.scigraph_data.url))])
            obj['iri'] = iri

        if lf in d:
            obj['label'] = d[lf]

        cf = fname + "_category"
        if cf in d:
            obj['category'] = [d[cf]]

        if 'aspect' in d and id.startswith('GO:'):
            obj['category'] = [ASPECT_MAP[d['aspect']]]
            del d['aspect']

        return obj
390823
def from_dict(cls, d):
        
        def _lnk(o):
            return None if o is None else Lnk.charspan(o['from'], o['to'])
        def _ep(ep):
            return ElementaryPredication(
                nodeid=None,
                pred=Pred.surface_or_abstract(ep['predicate']),
                label=ep['label'],
                args=ep.get('arguments', {}),
                lnk=_lnk(ep.get('lnk')),
                surface=ep.get('surface'),
                base=ep.get('base')
            )
        eps = [_ep(rel) for rel in d.get('relations', [])]
        hcons = [(c['high'], c['relation'], c['low'])
                 for c in d.get('constraints', []) if 'high' in c]
        icons = [(c['high'], c['relation'], c['low'])
                 for c in d.get('constraints', []) if 'left' in c]
        variables = {var: list(data.get('properties', {}).items())
                     for var, data in d.get('variables', {}).items()}
        return cls(
            top=d.get('top'),
            index=d.get('index'),
            xarg=d.get('xarg'),
            rels=eps,
            hcons=hcons,
            icons=icons,
            lnk=_lnk(d.get('lnk')),
            surface=d.get('surface'),
            identifier=d.get('identifier'),
            vars=variables
        )
672617
def from_old_dict(cls, d):
        
        # Strip the label to recover initial string (see trick used in as_dict to handle $ chars)
        labels_dict = {k.strip(): v for k, v in d['labels_dict'].items()}
        projections = {}
        structure = None
        if 'projections' in d and len(d['projections']) != 0:
            structure = Structure.from_dict(d['structure'])
            projections = {}
            for spin in d['projections']:
                dd = []
                for i in range(len(d['projections'][spin])):
                    ddd = []
                    for j in range(len(d['projections'][spin][i])):
                        dddd = []
                        for k in range(len(d['projections'][spin][i][j])):
                            ddddd = []
                            orb = Orbital(k).name
                            for l in range(len(d['projections'][spin][i][j][
                                                   orb])):
                                ddddd.append(d['projections'][spin][i][j][
                                                 orb][l])
                            dddd.append(np.array(ddddd))
                        ddd.append(np.array(dddd))
                    dd.append(np.array(ddd))
                projections[Spin(int(spin))] = np.array(dd)

        return BandStructureSymmLine(
            d['kpoints'], {Spin(int(k)): d['bands'][k]
                           for k in d['bands']},
            Lattice(d['lattice_rec']['matrix']), d['efermi'],
            labels_dict, structure=structure, projections=projections)
925029
def flatten_dict(d, prefix='', sep='.'):
    
    def apply_and_resolve_conflicts(dest, item, prefix):
        for k, v in flatten_dict(item, prefix=prefix, sep=sep).items():
            new_key = k
            i = 2
            while new_key in d:
                new_key = '{key}{sep}{index}'.format(key=k, sep=sep, index=i)
                i += 1
            dest[new_key] = v

    for key in list(d.keys()):
        if any(unicode(prefix)):
            new_key = u'{p}{sep}{key}'.format(p=prefix, key=key, sep=sep)
        else:
            new_key = key
        if isinstance(d[key], (dict, collections.Mapping)):
            apply_and_resolve_conflicts(d, d.pop(key), new_key)
        elif isinstance(d[key], six.string_types):
            d[new_key] = d.pop(key)
        elif isinstance(d[key], (list, collections.Mapping)):
            array = d.pop(key)
            for i in range(len(array)):
                index_key = '{key}{sep}{i}'.format(key=key, sep=sep, i=i)
                while index_key in d:
                    i += 1
                apply_and_resolve_conflicts(d, array[i], index_key)
        else:
            d[new_key] = d.pop(key)
    return d
1177731
def dot(graph, simple=True, debug=False, landscape=False):
    """"""
    import sys

    from rdflib import ConjunctiveGraph
    from rdflib.plugin import register, Parser
    from rdflib.tools.rdf2dot import rdf2dot

    register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')

    g = ConjunctiveGraph().parse(
        data=_jsonld(graph, 'expand'),
        format='json-ld',
    )

    g.bind('prov', 'http://www.w3.org/ns/prov#')
    g.bind('wfdesc', 'http://purl.org/wf4ever/wfdesc#')
    g.bind('wf', 'http://www.w3.org/2005/01/wf/flow#')
    g.bind('wfprov', 'http://purl.org/wf4ever/wfprov#')

    if debug:
        rdf2dot(g, sys.stdout)
        return

    sys.stdout.write('digraph { \n node [ fontname="DejaVu Sans" ] ; \n ')
    if landscape:
        sys.stdout.write('rankdir="LR" \n')
    if simple:
        _rdf2dot_simple(g, sys.stdout)
        return
    _rdf2dot_reduced(g, sys.stdout)
32060
def __serializedDot(self):
		
		temp = ""
		for x,y,z in self.rdflib_graph.triples((None, None, None)):
			temp += """"%s" -> "%s" [label="%s"];\n""" % (self.namespace_manager.normalizeUri(x), self.namespace_manager.normalizeUri(z), self.namespace_manager.normalizeUri(y))
		temp = "digraph graphname {\n%s}" % temp
		return temp
485365
def mapper_graph(df, lens_data=None, lens='pca', resolution=10, gain=0.5, equalize=True, clust='kmeans', stat='db',
                 max_K=5):
    
    if lens_data is None:
        lens_data = apply_lens(df, lens=lens)

    patch_clusterings = {}
    counter = 0
    patches = covering_patches(lens_data, resolution=resolution, gain=gain, equalize=equalize)
    for key, patch in patches.items():
        if len(patch) > 0:
            patch_clusterings[key] = optimal_clustering(df, patch, method=clust, statistic=stat, max_K=max_K)
            counter += 1
    print 'total of {} patches required clustering'.format(counter)

    all_clusters = []
    for key in patch_clusterings:
        all_clusters += patch_clusterings[key]
    num_nodes = len(all_clusters)
    print 'this implies {} nodes in the mapper graph'.format(num_nodes)

    A = np.zeros((num_nodes, num_nodes))
    for i in range(num_nodes):
        for j in range(i):
            overlap = set(all_clusters[i]).intersection(set(all_clusters[j]))
            if len(overlap) > 0:
                A[i, j] = 1
                A[j, i] = 1

    G = nx.from_numpy_matrix(A)
    total = []
    all_clusters_new = []
    mapping = {}
    cont = 0
    for m in all_clusters:
        total += m
    for n, m in enumerate(all_clusters):
        if len(m) == 1 and total.count(m) > 1:
            G.remove_node(n)
        else:
            all_clusters_new.append(m)
            mapping[n] = cont
            cont += 1
    H = nx.relabel_nodes(G, mapping)
    return H, all_clusters_new, patches
388428
def from_dict(cls, d):
        
        s = Structure.from_dict(d['structure'])
        return cls(s, d['graphs'])
15332
def format(self, vertices):
        
        index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
        com = ' '.join(self.vnames)  # for comment
        return '({0:s})  // {1:s} ({2:s})'.format(index, self.name, com)
582616
def to_dict(self, instance, d):
        

        value = self.__get__(instance, type(instance))
        if value == self.default:
            return

        d[self.tag] = self.type_.format(value)
734181
def multidict(D):
    ''''''
    keys = list(D.keys())
    if len(keys) == 0:
        return [[]]
    try:
        N = len(D[keys[0]])
        islist = True
    except:
        N = 1
        islist = False
    dlist = [dict() for d in range(N)]
    for k in keys:
        if islist:
            for i in range(N):
                dlist[i][k] = D[k][i]
        else:
            dlist[0][k] = D[k]
    return [keys]+dlist
816503
def docify(self, df):
        
        dtypes = {}
        masks = {}
        lengths = {}
        columns = []
        data = Binary(b'')
        start = 0

        arrays = []
        for c in df:
            try:
                columns.append(str(c))
                arr, mask = self._convert_types(df[c].values)
                dtypes[str(c)] = arr.dtype.str
                if mask is not None:
                    masks[str(c)] = Binary(compress(mask.tostring()))
                arrays.append(arr.tostring())
            except Exception as e:
                typ = infer_dtype(df[c], skipna=False)
                msg = "Column '{}' type is {}".format(str(c), typ)
                logging.info(msg)
                raise e

        arrays = compress_array(arrays)
        for index, c in enumerate(df):
            d = Binary(arrays[index])
            lengths[str(c)] = (start, start + len(d) - 1)
            start += len(d)
            data += d

        doc = SON({DATA: data, METADATA: {}})
        doc[METADATA] = {COLUMNS: columns,
                         MASK: masks,
                         LENGTHS: lengths,
                         DTYPE: dtypes
                         }

        return doc
212354
def _get_factors(self, element):
        
        xdim, ydim = element.dimensions()[:2]
        xvals, yvals = [element.dimension_values(i, False)
                        for i in range(2)]
        coords = tuple([v if vals.dtype.kind in 'SU' else dim.pprint_value(v) for v in vals]
                  for dim, vals in [(xdim, xvals), (ydim, yvals)])
        if self.invert_axes: coords = coords[::-1]
        return coords
1106254
def map_keys(f, dct):
    
    f_dict = {}
    for k, v in dct.items():
        f_dict[f(k)] = v
    return f_dict
775730
def get_subgraphs_by_citation(graph):
    
    rv = defaultdict(graph.fresh_copy)

    for u, v, key, data in graph.edges(keys=True, data=True):
        if CITATION not in data:
            continue
        dk = data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]

        rv[dk].add_edge(u, v, key=key, **data)

    cleanup(graph, rv)

    return dict(rv)
1259051
def asDictionary(self):
        """"""
        feat_dict = {}
        if self._geom is not None:
            if 'feature' in self._dict:
                feat_dict['geometry'] = self._dict['feature']['geometry']
            elif 'geometry' in self._dict:
                feat_dict['geometry'] =  self._dict['geometry']
        if 'feature' in self._dict:
            feat_dict['attributes'] = self._dict['feature']['attributes']
        else:
            feat_dict['attributes'] = self._dict['attributes']
        return self._dict