code: def collapse(self, weight_attr='weight'):
          
  
          if self.directed:
              graph = nx.DiGraph()
          else:
              graph = nx.Graph()
  
          # Transfer all nodes and attributes.
          for n, attrs in self.master_graph.nodes(data=True):
              graph.add_node(n, attrs)
  
          for s, t, attrs in self.master_graph.edges(data=True):
              if not graph.has_edge(s, t):
                  graph.add_edge(s, t)
  
              if 'weight' not in graph[s][t]:
                  graph[s][t]['weight'] = 0.
              if weight_attr in attrs:
                  graph[s][t]['weight'] += attrs[weight_attr]
              else:
                  graph[s][t]['weight'] += 1.
  
              gname = attrs['graph']
              for k, v in attrs.iteritems():
                  if k in [weight_attr, 'graph']:
                      continue
                  if k not in graph[s][t]:
                      graph[s][t][k] = {}
                  graph[s][t][k][gname] = v
          return graph
docs: Returns a :ref:`networkx.Graph <networkx:graph>` or :class:`networkx.DiGraph` in which
          the edges between each pair of nodes are collapsed into a single
          weighted edge.