code: def busmap_by_stubs(network, matching_attrs=None):
      
  
      busmap = pd.Series(network.buses.index, network.buses.index)
  
      G = network.graph()
  
      def attrs_match(u, v):
          return (matching_attrs is None or
                  (network.buses.loc[u, matching_attrs] ==
                   network.buses.loc[v, matching_attrs]).all())
  
      while True:
          stubs = []
          for u in G.node:
              neighbours = list(G.adj[u].keys())
              if len(neighbours) == 1:
                  v, = neighbours
                  if attrs_match(u, v):
                      busmap[busmap == u] = v
                      stubs.append(u)
          G.remove_nodes_from(stubs)
          if len(stubs) == 0:
              break
      return busmap
docs: Create a busmap by reducing stubs and stubby trees
      (i.e. sequentially reducing dead-ends).
  
      Parameters
      ----------
      network : pypsa.Network
  
      matching_attrs : None|[str]
          bus attributes clusters have to agree on
  
      Returns
      -------
      busmap : pandas.Series
          Mapping of network.buses to k-means clusters (indexed by
          non-negative integers).